Java Code Examples for java.math.BigInteger#and()

The following examples show how to use java.math.BigInteger#and() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: j2objc   File: BigIntegerAndTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * And for zero and a negative number
 */
public void testZeroNeg() {
    byte aBytes[] = {0};
    byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23};
    int aSign = 0;
    int bSign = -1;        
    byte rBytes[] = {0};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.and(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 0, result.signum());
}
 
Example 2
Source Project: ghidra   File: OpBehaviorSubpiece.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BigInteger evaluateBinary(int sizeout, int sizein, BigInteger in1, BigInteger in2) {
	// must eliminate sign extension bits produced by BigInteger.shiftRight
	int signbit = (sizein * 8) - 1;
	BigInteger res = in1;
	boolean negative = res.testBit(signbit);
	if (negative) {
		res = res.and(Utils.calc_bigmask(sizein));
		res = res.clearBit(signbit);
	}
	int shift = in2.intValue() * 8;
	res = res.shiftRight(shift);
	signbit -= shift;
	if (negative && signbit >= 0) {
		res = res.setBit(signbit); // restore shifted sign bit
	}
	return res;
}
 
Example 3
Source Project: tutorials   File: BigIntegerDemoUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() {
    BigInteger i = new BigInteger("17");
    BigInteger j = new BigInteger("7");

    BigInteger and = i.and(j);
    BigInteger or = i.or(j);
    BigInteger not = j.not();
    BigInteger xor = i.xor(j);
    BigInteger andNot = i.andNot(j);
    BigInteger shiftLeft = i.shiftLeft(1);
    BigInteger shiftRight = i.shiftRight(1);

    assertEquals(new BigInteger("1"), and);
    assertEquals(new BigInteger("23"), or);
    assertEquals(new BigInteger("-8"), not);
    assertEquals(new BigInteger("22"), xor);
    assertEquals(new BigInteger("16"), andNot);
    assertEquals(new BigInteger("34"), shiftLeft);
    assertEquals(new BigInteger("8"), shiftRight);
}
 
Example 4
Source Project: j2objc   File: BigIntegerAndTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * And for zero and a positive number
 */
public void testZeroPos() {
    byte aBytes[] = {0};
    byte bBytes[] = {-2, -3, -4, -4, 5, 14, 23, 39, 48, 57, 66, 5, 14, 23};
    int aSign = 0;
    int bSign = 1;        
    byte rBytes[] = {0};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger bNumber = new BigInteger(bSign, bBytes);
    BigInteger result = aNumber.and(bNumber);
    byte resBytes[] = new byte[rBytes.length];
    resBytes = result.toByteArray();
    for(int i = 0; i < resBytes.length; i++) {
        assertTrue(resBytes[i] == rBytes[i]);
    }
    assertEquals("incorrect sign", 0, result.signum());
}
 
Example 5
Source Project: Web-API   File: CIDRAddress.java    License: MIT License 5 votes vote down vote up
private void calculate() throws UnknownHostException {
    ByteBuffer maskBuffer;
    int targetSize;
    if (inetAddress.getAddress().length == 4) {
        maskBuffer =
                ByteBuffer
                        .allocate(4)
                        .putInt(-1);
        targetSize = 4;
    } else {
        maskBuffer = ByteBuffer.allocate(16)
                .putLong(-1L)
                .putLong(-1L);
        targetSize = 16;
    }

    BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);

    ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    BigInteger ipVal = new BigInteger(1, buffer.array());

    BigInteger startIp = ipVal.and(mask);
    BigInteger endIp = startIp.add(mask.not());

    byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
    byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);

    this.startAddress = InetAddress.getByAddress(startIpArr);
    this.endAddress = InetAddress.getByAddress(endIpArr);

}
 
Example 6
@Override
public BigInteger valInt() {
    if (args.get(0).isNullValue()) {
        nullValue = true; /* purecov: inspected */
        return BigInteger.ZERO; /* purecov: inspected */
    }
    if (args.get(1).isNullValue()) {
        nullValue = true;
        return BigInteger.ZERO;
    }
    nullValue = false;
    BigInteger arg1 = args.get(0).valInt();
    BigInteger arg2 = args.get(1).valInt();
    return arg1.and(arg2);
}
 
Example 7
Source Project: incubator-hivemall   File: PopcountUDF.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Count bits that both bits are 1.
 */
public IntWritable evaluate(String a, String b) {
    BigInteger ai = new BigInteger(a);
    BigInteger bi = new BigInteger(b);
    BigInteger innerProduct = ai.and(bi);
    return val(innerProduct.bitCount());
}
 
Example 8
Source Project: soltix   File: IntegerValue.java    License: Apache License 2.0 5 votes vote down vote up
public IntegerValue convertToIntegerType(ASTElementaryTypeName newType) throws Exception {
    IntegerValue result;
    // TODO actually adjust value.
    if (haveSmallValue()) {
        throw new Exception("Small values are unsupported");
        //result = new IntegerValue(otherType, getSmallValue());
    }

    BigInteger bigIntegerResult = getBigValue();

    // First construct a dummy value (which cannot be cached) with the result type so that proper bitmasks for these
    // conversions are already available within that object
    result = new IntegerValue(newType, bigIntegerResult);

    if (!newType.isSigned()) {
        // Mask off excess bits (truncate)
        result.prepareBitmasks();
        bigIntegerResult = bigIntegerResult.and(result.negationMask);
    } else {
        // Mask off excess bits (truncate)
        result.prepareBitmasks();
        bigIntegerResult = bigIntegerResult.and(result.negationMask);

        // Treat sign
        bigIntegerResult = result.makeSigned(bigIntegerResult);
    }

    result.updateValue(bigIntegerResult);

    return result.invariantChecked(result);
}
 
Example 9
BigInteger montgomeryMultiply(BigInteger a, BigInteger b, BigInteger N,
        int len, BigInteger n_prime)
        throws Throwable {
    BigInteger T = a.multiply(b);
    BigInteger R = BigInteger.ONE.shiftLeft(len*32);
    BigInteger mask = R.subtract(BigInteger.ONE);
    BigInteger m = (T.and(mask)).multiply(n_prime);
    m = m.and(mask); // i.e. m.mod(R)
    T = T.add(m.multiply(N));
    T = T.shiftRight(len*32); // i.e. T.divide(R)
    if (T.compareTo(N) > 0) {
        T = T.subtract(N);
    }
    return T;
}
 
Example 10
Source Project: j2objc   File: BigIntegerOrTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testRegression() {
    // Regression test for HARMONY-1996
    BigInteger x = new BigInteger("-1023");
    BigInteger r1 = x.and((BigInteger.ZERO.not()).shiftLeft(32));
    BigInteger r3 = x.and((BigInteger.ZERO.not().shiftLeft(32) ).not());
    BigInteger result = r1.or(r3);
    assertEquals(x, result);
}
 
Example 11
Source Project: dble   File: MySQLcom.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static BigInteger getUnsignedLong(long l) {
    BigInteger bi = BigInteger.valueOf(l);
    BigInteger bmask = new BigInteger("FFFFFFFFFFFFFFFF", 16);
    return bi.and(bmask);
}
 
Example 12
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
	final BlockStore blockStore) throws VerificationException, BlockStoreException {
    final Block prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev.getHeight())) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() +
                    ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " +
                    Long.toHexString(prev.getDifficultyTarget()));
        return;
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    Sha256Hash hash = prev.getHash();
    StoredBlock cursor = null;
    final int interval = this.getInterval();
    for (int i = 0; i < interval; i++) {
        cursor = blockStore.get(hash);
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the last transition point. Not found: " + hash);
        }
        hash = cursor.getHeader().getPrevBlockHash();
    }
    checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1),
            "Didn't arrive at a transition point.");
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}
 
Example 13
Source Project: bitherj   File: Block.java    License: Apache License 2.0 4 votes vote down vote up
public void verifyDifficultyFromPreviousBlock(Block prev, int transitionTime) {
        // checkState(lock.isHeldByCurrentThread());

        // Is this supposed to be a difficulty transition point?
        if ((prev.getBlockNo() + 1) % BitherjSettings.BLOCK_DIFFICULTY_INTERVAL != 0) {

            // TODO: Refactor this hack after 0.5 is released and we stop supporting deserialization compatibility.
            // This should be a method of the NetworkParameters, which should in turn be using singletons and a subclass
            // for each network type. Then each network can define its own difficulty transition rules.
//            if (Settings.params.getId().equals(NetworkParameters.ID_TESTNET) && nextBlock.getTime().after(testnetDiffDate)) {
//                checkTestnetDifficulty(storedPrev, prev, nextBlock);
//                return;
//            }

            // No ... so check the difficulty didn't actually change.
            if (this.getBlockBits() != prev.getBlockBits())
                throw new VerificationException("Unexpected change in difficulty at height " + prev.getBlockNo() +
                        ": " + Long.toHexString(this.getBlockBits()) + " vs " +
                        Long.toHexString(prev.getBlockBits()));
            return;
        }

        // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
        // two weeks after the initial block chain download.
//        long now = System.currentTimeMillis();
//        Block cursor = get(prev.getBlockHash());
//        for (int i = 0; i < BitherjSettings.BLOCK_DIFFICULTY_INTERVAL - 1; i++) {
//            if (cursor == null) {
//                // This should never happen. If it does, it means we are following an incorrect or busted chain.
//                throw new VerificationException(
//                        "Difficulty transition point but we did not find a way back to the genesis block.");
//            }
//            cursor = get(cursor.getBlockPrev());
//        }
//        long elapsed = System.currentTimeMillis() - now;
//        if (elapsed > 50)
//            log.info("Difficulty transition traversal took {}msec", elapsed);
//
//        Block blockIntervalAgo = cursor;
//        int timespan = (int) (prev.getBlockTime() - blockIntervalAgo.getBlockTime());
        int timespan = (int) (prev.getBlockTime() - transitionTime);
        // Limit the adjustment step.
        final int targetTimespan = BitherjSettings.TARGET_TIMESPAN;
        if (timespan < targetTimespan / 4)
            timespan = targetTimespan / 4;
        if (timespan > targetTimespan * 4)
            timespan = targetTimespan * 4;

        BigInteger newDifficulty = Utils.decodeCompactBits(prev.getBlockBits());
        newDifficulty = newDifficulty.multiply(BigInteger.valueOf(timespan));
        newDifficulty = newDifficulty.divide(BigInteger.valueOf(targetTimespan));

        if (newDifficulty.compareTo(BitherjSettings.proofOfWorkLimit) > 0) {
            // log.info("Difficulty hit proof of work limit: {}", newDifficulty.toString(16));
            newDifficulty = BitherjSettings.proofOfWorkLimit;
        }

        int accuracyBytes = (int) (this.getBlockBits() >>> 24) - 3;
        BigInteger receivedDifficulty = this.getDifficultyTargetAsInteger();

        // The calculated difficulty is to a higher precision than received, so reduce here.
        BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
        newDifficulty = newDifficulty.and(mask);

        if (newDifficulty.compareTo(receivedDifficulty) != 0)
            throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                    receivedDifficulty.toString(16) + " vs " + newDifficulty.toString(16));
    }
 
Example 14
@Override
public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock,
	final BlockStore blockStore) throws VerificationException, BlockStoreException {
    final Block prev = storedPrev.getHeader();

    // Is this supposed to be a difficulty transition point?
    if (!isDifficultyTransitionPoint(storedPrev.getHeight())) {

        // No ... so check the difficulty didn't actually change.
        if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget())
            throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() +
                    ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " +
                    Long.toHexString(prev.getDifficultyTarget()));
        return;
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every
    // two weeks after the initial block chain download.
    final Stopwatch watch = Stopwatch.createStarted();
    Sha256Hash hash = prev.getHash();
    StoredBlock cursor = null;
    final int interval = this.getInterval();
    for (int i = 0; i < interval; i++) {
        cursor = blockStore.get(hash);
        if (cursor == null) {
            // This should never happen. If it does, it means we are following an incorrect or busted chain.
            throw new VerificationException(
                    "Difficulty transition point but we did not find a way back to the last transition point. Not found: " + hash);
        }
        hash = cursor.getHeader().getPrevBlockHash();
    }
    checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1),
            "Didn't arrive at a transition point.");
    watch.stop();
    if (watch.elapsed(TimeUnit.MILLISECONDS) > 50)
        log.info("Difficulty transition traversal took {}", watch);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds());
    // Limit the adjustment step.
    final int targetTimespan = this.getTargetTimespan();
    if (timespan < targetTimespan / 4)
        timespan = targetTimespan / 4;
    if (timespan > targetTimespan * 4)
        timespan = targetTimespan * 4;

    BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget());
    newTarget = newTarget.multiply(BigInteger.valueOf(timespan));
    newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan));

    if (newTarget.compareTo(this.getMaxTarget()) > 0) {
        log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16));
        newTarget = this.getMaxTarget();
    }

    int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3;
    long receivedTargetCompact = nextBlock.getDifficultyTarget();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newTarget = newTarget.and(mask);
    long newTargetCompact = Utils.encodeCompactBits(newTarget);

    if (newTargetCompact != receivedTargetCompact)
        throw new VerificationException("Network provided difficulty bits do not match what was calculated: " +
                Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact));
}
 
Example 15
Source Project: ghidra   File: OpBehaviorIntAnd.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger evaluateBinary(int sizeout, int sizein, BigInteger in1, BigInteger in2) {
	BigInteger res = in1.and(in2);
	return res;
}
 
Example 16
Source Project: pitest   File: BigIntegerMutatorTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
BigInteger apply(BigInteger left, BigInteger right) {
  return left.and(right);
}
 
Example 17
Source Project: imagej-ops   File: Types.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static BigInteger uint64(final long value) { 
	BigInteger original = BigInteger.valueOf(value);
	return original.and(maskU64);
}
 
Example 18
Source Project: AVM   File: BigIntegerTarget.java    License: MIT License 4 votes vote down vote up
@Callable
public static byte[] and(byte[] val) {
    BigInteger testValue = new BigInteger(val);
    BigInteger result = testValue.and(testValue);
    return result.toByteArray();
}
 
Example 19
Source Project: symbol-sdk-java   File: ConvertUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * It converts a signed BigInteger into an unsigned BigInteger. It fixes overflow problems that
 * could happen when working with unsigned int 64.
 *
 * @param value the value, positive or negative.
 * @return the positive {@link BigInteger}.
 */
public static BigInteger toUnsignedBigInteger(BigInteger value) {
    return value.and(UNSIGNED_LONG_MASK);
}
 
Example 20
public static BigInteger uint128(final BigInteger value) { return value.and(mask128); }