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

The following examples show how to use java.math.BigInteger#shiftLeft() . 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: es6draft   File: BigIntType.java    License: MIT License 6 votes vote down vote up
/**
 * BigInt::leftShift (x, y)
 * 
 * @param cx
 *            the execution context
 * @param x
 *            the x value
 * @param y
 *            the y value
 * @return the result of left-shifting {@code x} by {@code y}
 */
public static BigInteger leftShift(ExecutionContext cx, BigInteger x, BigInteger y) {
    if (x.signum() == 0) {
        return BigInteger.ZERO;
    }
    if (y.signum() == 0) {
        return x;
    }
    if (y.bitLength() > 31) {
        if (y.signum() > 0) {
            throw newRangeError(cx, Messages.Key.BigIntValueTooLarge);
        }
        return BigInteger.ZERO;
    }
    int yAsInt = y.intValueExact();
    try {
        return x.shiftLeft(yAsInt);
    } catch (ArithmeticException e) {
        throw newRangeError(cx, Messages.Key.BigIntValueTooLarge);
    }
}
 
Example 2
Source Project: kinesis-aggregation   File: AggRecord.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculate a new explicit hash key based on the input partition key (following
 * the algorithm from the original KPL).
 * 
 * @param partitionKey
 *            The partition key to seed the new explicit hash key with
 * @return An explicit hash key based on the input partition key generated using
 *         an algorithm from the original KPL.
 */
private String createExplicitHashKey(final String partitionKey) {
	BigInteger hashKey = BigInteger.ZERO;

	this.md5.reset();
	byte[] pkDigest = this.md5.digest(partitionKey.getBytes(StandardCharsets.UTF_8));

	for (int i = 0; i < this.md5.getDigestLength(); i++) {
		BigInteger p = new BigInteger(String.valueOf((int) pkDigest[i] & 0xFF)); // convert
																					// to
																					// unsigned
																					// integer
		BigInteger shifted = p.shiftLeft((16 - i - 1) * 8);
		hashKey = hashKey.add(shifted);
	}

	return hashKey.toString(10);
}
 
Example 3
/**
 * Lower bound for the harmonic number H_n.
 * From https://math.stackexchange.com/questions/306371/simple-proof-of-showing-the-harmonic-number-h-n-theta-log-n:
 * H_n = ln(n) + gamma + 1/2*n^-1 - 1/12*n^-2 + 1/120*n^-4 - 1/252*n^-6 + O(n^-8)
 * 
 * @param n
 * @param scale number of exact after-komma digits
 * @return lower bound for the harmonic number H_n
 */
// TODO larger series expansion using Bernoulli numbers, see https://en.wikipedia.org/wiki/Harmonic_number#Calculation
public static BigDecimal harmonic_lowerBound(BigInteger n, Scale scale) {
	BigDecimal result = EulerConstant.gamma(scale);
	result.setScale(scale.digits(), RoundingMode.FLOOR);
	result = result.add(Ln.ln(new BigDecimal(n), scale));
	BigInteger den = n.shiftLeft(1); // 2n
	result = result.add(F_1.divide(new BigDecimal(den), scale.digits(), RoundingMode.HALF_EVEN));
	den = den.multiply(I_6).multiply(n); // 12 n^2
	result = result.subtract(F_1.divide(new BigDecimal(den), scale.digits(), RoundingMode.HALF_EVEN));
	BigInteger nSquare = n.multiply(n);
	BigInteger tmp = den.multiply(nSquare); // 12 n^4
	den = tmp.multiply(I_10); // 120 n^4
	result = result.add(F_1.divide(new BigDecimal(den), scale.digits(), RoundingMode.HALF_EVEN));
	den = tmp.multiply(I_21).multiply(nSquare); // 252 n^6
	result = result.subtract(F_1.divide(new BigDecimal(den), scale.digits(), RoundingMode.HALF_EVEN));
	return result;
}
 
Example 4
Source Project: JImageHash   File: FuzzyHash.java    License: MIT License 6 votes vote down vote up
/**
 * Escape the given hash the same way {@link #getUncertaintyHash(double)}
 * escapes this fuzzy hash.
 * <p>
 * Return a simple hash containing only the bits that are below the specified
 * uncertainty of the fuzzy hash. This hash can be used to further compare
 * hashes matched to this cluster while ignoring bits that are likely to be
 * similar.
 * 
 * <p>
 * To get reasonable results the source hash has to be compatible with the fuzzy
 * hash, meaning that it was generated by the same algorithm and settings as the
 * hashes which make up the fuzzy hash.
 * 
 * @param source    the hash to convert.
 * @param certainty threshold to indicate which bits to discard
 * @return a hash with the certain bits discarded.
 */
public Hash toUncertaintyHash(Hash source, double certainty) {

	ensureUpToDateWeights();

	int bitCount = getBitResolution();
	BigInteger hashValue = BigInteger.ZERO;

	int newBitCount = 0;
	int hashCode = algorithmId;
	for (int i = 0; i < bitCount; i++) {
		if (!(bitWeights[i] > certainty || bitWeights[i] < -certainty)) {
			if (source.getBitUnsafe(i)) {
				hashValue = hashValue.shiftLeft(1).add(BigInteger.ONE);
			} else {
				hashValue = hashValue.shiftLeft(1);
			}
			newBitCount++;
			hashCode = 31 * hashCode + i;
		}
	}
	return new Hash(hashValue, newBitCount, 31 * hashCode + newBitCount);
}
 
Example 5
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 6
Source Project: presto   File: TestDecimalStream.java    License: Apache License 2.0 5 votes vote down vote up
private static void writeBigInteger(OutputStream output, BigInteger value)
        throws IOException
{
    // encode the signed number as a positive integer
    value = value.shiftLeft(1);
    int sign = value.signum();
    if (sign < 0) {
        value = value.negate();
        value = value.subtract(ONE);
    }
    int length = value.bitLength();
    while (true) {
        long lowBits = value.longValue() & 0x7fffffffffffffffL;
        length -= 63;
        // write out the next 63 bits worth of data
        for (int i = 0; i < 9; ++i) {
            // if this is the last byte, leave the high bit off
            if (length <= 0 && (lowBits & ~0x7f) == 0) {
                output.write((byte) lowBits);
                return;
            }
            else {
                output.write((byte) (0x80 | (lowBits & 0x7f)));
                lowBits >>>= 7;
            }
        }
        value = value.shiftRight(63);
    }
}
 
Example 7
/**
 * Multiply BigInteger by powers of 5 and 2 (i.e., 10)
 * @param value Value to multiply.
 * @param p5    Power of 5.
 * @param p2    Power of 2.
 * @return Result.
 */
private static BigInteger multiplyPowerOf5And2(final BigInteger value, final int p5, final int p2) {
    BigInteger returnValue = value;

    if (p5 != 0) {
        returnValue = returnValue.multiply(bigPowerOf5(p5));
    }

    if (p2 != 0) {
        returnValue = returnValue.shiftLeft(p2);
    }

    return returnValue;
}
 
Example 8
Source Project: keycloak   File: UInt64.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a UInt64 from two longs.
 *
 * @param top    Most significant 4 bytes.
 * @param bottom Least significant 4 bytes.
 */
public UInt64(long top, long bottom) {
    BigInteger a = new BigInteger("" + top);
    a = a.shiftLeft(32);
    a = a.add(new BigInteger("" + bottom));
    if (0 > a.compareTo(BigInteger.ZERO))
        throw new NumberFormatException(MessageFormat.format(getString("isNotBetween"), new Object[]{a, MIN_VALUE, MAX_BIG_VALUE}));
    if (0 < a.compareTo(MAX_BIG_VALUE))
        throw new NumberFormatException(MessageFormat.format(getString("isNotBetween"), new Object[]{a, MIN_VALUE, MAX_BIG_VALUE}));
    this.value = a;
    this.top = top;
    this.bottom = bottom;
}
 
Example 9
/**
 * shiftLeft(int n), n = 0
 */
public void testShiftLeft1() {
    byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26};
    int aSign = 1;
    int number = 0;
    byte rBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger result = aNumber.shiftLeft(number);
    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", 1, result.signum());
}
 
Example 10
/**
 * Construct a BigInteger power of 5 and 2 (i.e., 10)
 * @param p5    Power of 5.
 * @param p2    Power of 2.
 * @return Result.
 */
private static BigInteger constructPowerOf5And2(final int p5, final int p2) {
    BigInteger v = bigPowerOf5(p5);

    if (p2 != 0) {
        v = v.shiftLeft(p2);
    }

    return v;
}
 
Example 11
Source Project: j2objc   File: BigIntegerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.math.BigInteger#shiftLeft(int)
 */
public void test_shiftLeftI() {
	assertTrue("1 << 0", one.shiftLeft(0).equals(one));
	assertTrue("1 << 1", one.shiftLeft(1).equals(two));
	assertTrue("1 << 63", one.shiftLeft(63).equals(
			new BigInteger("8000000000000000", 16)));
	assertTrue("1 << 64", one.shiftLeft(64).equals(
			new BigInteger("10000000000000000", 16)));
	assertTrue("1 << 65", one.shiftLeft(65).equals(
			new BigInteger("20000000000000000", 16)));
	assertTrue("-1 << 0", minusOne.shiftLeft(0).equals(minusOne));
	assertTrue("-1 << 1", minusOne.shiftLeft(1).equals(minusTwo));
	assertTrue("-1 << 63", minusOne.shiftLeft(63).equals(
			new BigInteger("-9223372036854775808")));
	assertTrue("-1 << 64", minusOne.shiftLeft(64).equals(
			new BigInteger("-18446744073709551616")));
	assertTrue("-1 << 65", minusOne.shiftLeft(65).equals(
			new BigInteger("-36893488147419103232")));

	BigInteger a = bi3;
	BigInteger c = minusOne;
	for (int i = 0; i < 200; i++) {
		BigInteger b = bi3.shiftLeft(i);
		assertTrue("a==b", a.equals(b));
		assertTrue("a >> i == bi3", a.shiftRight(i).equals(bi3));
		a = a.shiftLeft(1);
		assertTrue("<<1 == *2", b.multiply(two).equals(a));
		assertTrue("a non-neg", a.signum() >= 0);
		assertTrue("a.bitCount==b.bitCount", a.bitCount() == b.bitCount());

		BigInteger d = minusOne.shiftLeft(i);
		assertTrue("c==d", c.equals(d));
		c = c.shiftLeft(1);
		assertTrue("<<1 == *2 negative", d.multiply(two).equals(c));
		assertTrue("c negative", c.signum() == -1);
		assertTrue("d >> i == minusOne", d.shiftRight(i).equals(minusOne));
	}
}
 
Example 12
/**
 * Multiply BigInteger by powers of 5 and 2 (i.e., 10)
 * @param value Value to multiply.
 * @param p5    Power of 5.
 * @param p2    Power of 2.
 * @return Result.
 */
private static BigInteger multiplyPowerOf5And2(final BigInteger value, final int p5, final int p2) {
    BigInteger returnValue = value;

    if (p5 != 0) {
        returnValue = returnValue.multiply(bigPowerOf5(p5));
    }

    if (p2 != 0) {
        returnValue = returnValue.shiftLeft(p2);
    }

    return returnValue;
}
 
Example 13
/**
 * shiftLeft(int n), n < 0
 */
public void testShiftLeft2() {
    byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26};
    int aSign = 1;
    int number = -27;
    byte rBytes[] = {48, 7, 12, -97, -42, -117, 37, -85, 96};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger result = aNumber.shiftLeft(number);
    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", 1, result.signum());
}
 
Example 14
/**
 * shiftLeft(int n) a positive number, n > 0
 */
public void testShiftLeft4() {
    byte aBytes[] = {1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26};
    int aSign = 1;
    int number = 45;
    byte rBytes[] = {48, 7, 12, -97, -42, -117, 37, -85, 96, 126, 36, 99, 64, 0, 0, 0, 0, 0};
    BigInteger aNumber = new BigInteger(aSign, aBytes);
    BigInteger result = aNumber.shiftLeft(number);
    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", 1, result.signum());
}
 
Example 15
Source Project: web3j   File: FixedPointType.java    License: Apache License 2.0 5 votes vote down vote up
static BigInteger convert(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
    BigInteger mPadded = m.shiftLeft(nBitSize);
    int nBitLength = n.bitLength();

    // find next multiple of 4
    int shift = (nBitLength + 3) & ~0x03;
    return mPadded.or(n.shiftLeft(nBitSize - shift));
}
 
Example 16
/**
 * @return the rules packed into a single {@link BigInteger} value.
 */
public final BigInteger getRuleAsBigInt() {
    BigInteger r = BigInteger.ZERO;
    for (int i = rules.length - 1; i >= 0; i--) {
        r = r.shiftLeft(1);
        if (rules[i]) {
            r = r.setBit(0);
        }
    }
    return r;
}
 
Example 17
/**
 * Construct a BigInteger power of 5 and 2 (i.e., 10)
 * @param p5    Power of 5.
 * @param p2    Power of 2.
 * @return Result.
 */
private static BigInteger constructPowerOf5And2(final int p5, final int p2) {
    BigInteger v = bigPowerOf5(p5);

    if (p2 != 0) {
        v = v.shiftLeft(p2);
    }

    return v;
}
 
Example 18
Source Project: spring-vault   File: KeystoreUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static String getObjectIdentifier(byte bytes[]) {
	StringBuffer objId = new StringBuffer();
	long value = 0;
	BigInteger bigValue = null;
	boolean first = true;

	for (int i = 0; i != bytes.length; i++) {
		int b = bytes[i] & 0xff;

		if (value <= LONG_LIMIT) {
			value += (b & 0x7f);
			if ((b & 0x80) == 0) // end of number reached
			{
				if (first) {
					if (value < 40) {
						objId.append('0');
					}
					else if (value < 80) {
						objId.append('1');
						value -= 40;
					}
					else {
						objId.append('2');
						value -= 80;
					}
					first = false;
				}

				objId.append('.');
				objId.append(value);
				value = 0;
			}
			else {
				value <<= 7;
			}
		}
		else {
			if (bigValue == null) {
				bigValue = BigInteger.valueOf(value);
			}
			bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f));
			if ((b & 0x80) == 0) {
				if (first) {
					objId.append('2');
					bigValue = bigValue.subtract(BigInteger.valueOf(80));
					first = false;
				}

				objId.append('.');
				objId.append(bigValue);
				bigValue = null;
				value = 0;
			}
			else {
				bigValue = bigValue.shiftLeft(7);
			}
		}
	}

	return objId.toString();
}
 
Example 19
DERObjectIdentifier(
    byte[]  bytes)
{
    StringBuffer    objId = new StringBuffer();
    long            value = 0;
    BigInteger      bigValue = null;
    boolean         first = true;

    for (int i = 0; i != bytes.length; i++)
    {
        int b = bytes[i] & 0xff;

        if (value < 0x80000000000000L) 
        {
            value = value * 128 + (b & 0x7f);
            if ((b & 0x80) == 0)             // end of number reached
            {
                if (first)
                {
                    switch ((int)value / 40)
                    {
                    case 0:
                        objId.append('0');
                        break;
                    case 1:
                        objId.append('1');
                        value -= 40;
                        break;
                    default:
                        objId.append('2');
                        value -= 80;
                    }
                    first = false;
                }

                objId.append('.');
                objId.append(value);
                value = 0;
            }
        } 
        else 
        {
            if (bigValue == null)
            {
                bigValue = BigInteger.valueOf(value);
            }
            bigValue = bigValue.shiftLeft(7);
            bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f));
            if ((b & 0x80) == 0) 
            {
                objId.append('.');
                objId.append(bigValue);
                bigValue = null;
                value = 0;
            }
        }
    }

    this.identifier = objId.toString();
}
 
Example 20
Source Project: batfish   File: BDDDomain.java    License: Apache License 2.0 4 votes vote down vote up
public int ensureCapacity(BigInteger range) {
  BigInteger calcsize = BigInteger.valueOf(2L);
  if (range.signum() < 0) {
    throw new BDDException();
  }
  if (range.compareTo(realsize) < 0) {
    return ivar.length;
  }
  realsize = range.add(BigInteger.ONE);
  int binsize = 1;
  while (calcsize.compareTo(range) <= 0) {
    binsize++;
    calcsize = calcsize.shiftLeft(1);
  }
  if (ivar.length == binsize) {
    return binsize;
  }

  if (true) {
    throw new BDDException(
        "Can't add bits to domains, requested domain " + name + " upper limit " + range);
  }
  int[] new_ivar = new int[binsize];
  System.arraycopy(ivar, 0, new_ivar, 0, ivar.length);
  BDDFactory factory = getFactory();
  for (int i = ivar.length; i < new_ivar.length; ++i) {
    // System.out.println("Domain "+this+" Duplicating var#"+new_ivar[i-1]);
    int newVar = factory.duplicateVar(new_ivar[i - 1]);
    factory.firstbddvar++;
    new_ivar[i] = newVar;
    // System.out.println("Domain "+this+" var#"+i+" = "+newVar);
  }
  ivar = new_ivar;
  // System.out.println("Domain "+this+" old var = "+var);
  var.free();
  BDD nvar = factory.one();
  for (int i1 : ivar) {
    nvar.andWith(factory.ithVar(i1));
  }
  var = nvar;
  // System.out.println("Domain "+this+" new var = "+var);
  return binsize;
}