Java Code Examples for java.math.BigInteger#longValueExact()
The following examples show how to use
java.math.BigInteger#longValueExact() .
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 File: PrecompiledContracts.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
@Override public long getCpuForData(byte[] data) { if (data == null) { data = ByteUtil.EMPTY_BYTE_ARRAY; } int baseLen = parseLen(data, 0); int expLen = parseLen(data, 1); int modLen = parseLen(data, 2); byte[] expHighBytes = ByteUtil.parseBytes(data, BIUtil.addSafely(ARGS_OFFSET, baseLen), Math.min(expLen, 32)); long multComplexity = getMultComplexity(Math.max(baseLen, modLen)); long adjExpLen = getAdjustedExponentLength(expHighBytes, expLen); // use big numbers to stay safe in case of overflow BigInteger cpu = BigInteger.valueOf(multComplexity) .multiply(BigInteger.valueOf(Math.max(adjExpLen, 1))) .divide(GQUAD_DIVISOR); return BIUtil.isLessThan(cpu, BigInteger.valueOf(Long.MAX_VALUE)) ? cpu.longValueExact() : Long.MAX_VALUE; }
Example 2
Source File: VM.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
private long calcMemCpu(CpuCost cpuCosts, long oldMemSize, BigInteger newMemSize, long copySize, OpCode op) { long cpuCost = 0; checkMemorySize(op, newMemSize); // memory drop consume calc long memoryUsage = (newMemSize.longValueExact() + 31) / 32 * 32; if (memoryUsage > oldMemSize) { long memWords = (memoryUsage / 32); long memWordsOld = (oldMemSize / 32); //TODO #POC9 c_quadCoeffDiv = 512, this should be a constant, not magic number long memCpu = (cpuCosts.getMEMORY() * memWords + memWords * memWords / 512) - (cpuCosts.getMEMORY() * memWordsOld + memWordsOld * memWordsOld / 512); cpuCost += memCpu; } if (copySize > 0) { long copyCpu = cpuCosts.getCOPY_CPU() * ((copySize + 31) / 32); cpuCost += copyCpu; } return cpuCost; }
Example 3
Source File: Gas.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * Return a {@link Gas} containing the specified value. * * @param value The value to create a {@link Gas} for. * @return A {@link Gas} containing the specified value. * @throws IllegalArgumentException If the value is negative. */ public static Gas valueOf(BigInteger value) { checkArgument(value.signum() >= 0, "Argument must be positive"); if (value.compareTo(BI_MAX_CONSTANT) <= 0) { return CONSTANTS[value.intValue()]; } try { return new Gas(value.longValueExact()); } catch (ArithmeticException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Example 4
Source File: DecimalSaturatedFloorCasts.java From presto with Apache License 2.0 | 5 votes |
private static long bigIntegerDecimalToGenericIntegerType(BigInteger bigInteger, int sourceScale, long minValue, long maxValue) { BigDecimal bigDecimal = new BigDecimal(bigInteger, sourceScale); BigInteger unscaledValue = bigDecimal.setScale(0, FLOOR).unscaledValue(); if (unscaledValue.compareTo(BigInteger.valueOf(maxValue)) > 0) { return maxValue; } if (unscaledValue.compareTo(BigInteger.valueOf(minValue)) < 0) { return minValue; } return unscaledValue.longValueExact(); }
Example 5
Source File: TypeCalculation.java From presto with Apache License 2.0 | 5 votes |
public static Long calculateLiteralValue( String calculation, Map<String, Long> inputs) { try { ParserRuleContext tree = parseTypeCalculation(calculation); CalculateTypeVisitor visitor = new CalculateTypeVisitor(inputs); BigInteger result = visitor.visit(tree); return result.longValueExact(); } catch (StackOverflowError e) { throw new ParsingException("Type calculation is too large (stack overflow while parsing)"); } }
Example 6
Source File: Asn1BerParser.java From Xpatch with Apache License 2.0 | 5 votes |
private static long integerToLong(ByteBuffer encoded) throws Asn1DecodingException { BigInteger value = integerToBigInteger(encoded); try { return value.longValueExact(); } catch (ArithmeticException e) { throw new Asn1DecodingException( String.format("INTEGER cannot be represented as long: %1$d (0x%1$x)", value), e); } }
Example 7
Source File: Gas.java From cava with Apache License 2.0 | 5 votes |
/** * Return a {@link Gas} containing the specified value. * * @param value The value to create a {@link Gas} for. * @return A {@link Gas} containing the specified value. * @throws IllegalArgumentException If the value is negative. */ public static Gas valueOf(BigInteger value) { checkArgument(value.signum() >= 0, "Argument must be positive"); if (value.compareTo(BI_MAX_CONSTANT) <= 0) { return CONSTANTS[value.intValue()]; } try { return new Gas(value.longValueExact()); } catch (ArithmeticException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Example 8
Source File: TypeCalculation.java From rainbow with Apache License 2.0 | 5 votes |
public static Long calculateLiteralValue( String calculation, Map<String, Long> inputs) { try { ParserRuleContext tree = parseTypeCalculation(calculation); CalculateTypeVisitor visitor = new CalculateTypeVisitor(inputs); BigInteger result = visitor.visit(tree); return result.longValueExact(); } catch (StackOverflowError e) { throw new ParsingException("Type calculation is too large (stack overflow while parsing)"); } }
Example 9
Source File: MincodeParser.java From divolte-collector with Apache License 2.0 | 5 votes |
@SuppressWarnings("PMD.EmptyCatchBlock") private void setNumberValue(final BigInteger value) { _numTypesValid = NR_BIGINT; _numberBigInt = value; // Jackson expects all smaller types to be filled in, // so do this until they don't fit. try { _numberLong = value.longValueExact(); _numTypesValid |= NR_LONG; _numberInt = value.intValueExact(); _numTypesValid |= NR_INT; } catch (final ArithmeticException e) { // Harmless; means we reached a type into which it won't fit. } }
Example 10
Source File: JsonFormat.java From gsc-core with GNU Lesser General Public License v3.0 | 4 votes |
private static long parseInteger(String text, boolean isSigned, boolean isLong) throws NumberFormatException { int pos = 0; boolean negative = false; if (text.startsWith("-", pos)) { if (!isSigned) { throw new NumberFormatException("Number must be positive: " + text); } ++pos; negative = true; } int radix = 10; if (text.startsWith("0x", pos)) { pos += 2; radix = 16; } else if (text.startsWith("0", pos)) { radix = 8; } String numberText = text.substring(pos); long result = 0; if (numberText.length() < 16) { // Can safely assume no overflow. result = Long.parseLong(numberText, radix); if (negative) { result = -result; } // Check bounds. // No need to check for 64-bit numbers since they'd have to be 16 chars // or longer to overflow. if (!isLong) { if (isSigned) { if ((result > Integer.MAX_VALUE) || (result < Integer.MIN_VALUE)) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if ((result >= (1L << 32)) || (result < 0)) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } } else { BigInteger bigValue = new BigInteger(numberText, radix); if (negative) { bigValue = bigValue.negate(); } // Check bounds. if (!isLong) { if (isSigned) { if (bigValue.bitLength() > 31) { throw new NumberFormatException("Number out of range for 32-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 32) { throw new NumberFormatException("Number out of range for 32-bit unsigned integer: " + text); } } } else { if (isSigned) { if (bigValue.bitLength() > 63) { throw new NumberFormatException("Number out of range for 64-bit signed integer: " + text); } } else { if (bigValue.bitLength() > 64) { throw new NumberFormatException("Number out of range for 64-bit unsigned integer: " + text); } } } result = bigValue.longValueExact(); } return result; }
Example 11
Source File: Program.java From gsc-core with GNU Lesser General Public License v3.0 | 4 votes |
public static OutOfCpuException cpuOverflow(BigInteger actualCpu, BigInteger cpuLimit) { return new OutOfCpuException("Cpu value overflow: actualCpu[%d], cpuLimit[%d];", actualCpu.longValueExact(), cpuLimit.longValueExact()); }
Example 12
Source File: TestPointFields.java From lucene-solr with Apache License 2.0 | 4 votes |
@Test public void testLongPointFieldRangeFacet() throws Exception { String docValuesField = "number_p_l_dv"; String nonDocValuesField = "number_p_l"; int numValues = 10 * RANDOM_MULTIPLIER; int numBuckets = numValues / 2; List<Long> values; List<Long> sortedValues; long max; do { values = getRandomLongs(numValues, false); sortedValues = values.stream().sorted().collect(Collectors.toList()); } while ((max = sortedValues.get(sortedValues.size() - 1)) >= Long.MAX_VALUE - numValues); // leave room for rounding long min = sortedValues.get(0); BigInteger bigIntGap = BigInteger.valueOf(max + numValues).subtract(BigInteger.valueOf(min)) .divide(BigInteger.valueOf(numBuckets)); long gap = bigIntGap.longValueExact(); int[] bucketCount = new int[numBuckets]; int bucketNum = 0; long minBucketVal = min; // System.err.println("min:" + min + " max: " + max + " gap: " + gap); // System.err.println("bucketNum: " + bucketNum + " minBucketVal: " + minBucketVal); for (Long value : sortedValues) { // System.err.println("value: " + value); while (BigInteger.valueOf(value).subtract(BigInteger.valueOf(minBucketVal)).compareTo(bigIntGap) > 0) { ++bucketNum; minBucketVal += gap; // System.err.println("bucketNum: " + bucketNum + " minBucketVal: " + minBucketVal); } ++bucketCount[bucketNum]; } for (int i = 0 ; i < numValues ; i++) { assertU(adoc("id", String.valueOf(i), docValuesField, String.valueOf(values.get(i)), nonDocValuesField, String.valueOf(values.get(i)))); } assertU(commit()); assertTrue(h.getCore().getLatestSchema().getField(docValuesField).hasDocValues()); assertTrue(h.getCore().getLatestSchema().getField(docValuesField).getType() instanceof PointField); String[] testStrings = new String[numBuckets + 1]; testStrings[numBuckets] = "//*[@numFound='" + numValues + "']"; minBucketVal = min; for (int i = 0 ; i < numBuckets ; minBucketVal += gap, ++i) { testStrings[i] = "//lst[@name='facet_counts']/lst[@name='facet_ranges']/lst[@name='" + docValuesField + "']/lst[@name='counts']/int[@name='" + minBucketVal + "'][.='" + bucketCount[i] + "']"; } assertQ(req("q", "*:*", "facet", "true", "facet.range", docValuesField, "facet.range.start", String.valueOf(min), "facet.range.end", String.valueOf(max), "facet.range.gap", String.valueOf(gap)), testStrings); assertQ(req("q", "*:*", "facet", "true", "facet.range", docValuesField, "facet.range.start", String.valueOf(min), "facet.range.end", String.valueOf(max), "facet.range.gap", String.valueOf(gap), "facet.range.method", "dv"), testStrings); assertFalse(h.getCore().getLatestSchema().getField(nonDocValuesField).hasDocValues()); assertTrue(h.getCore().getLatestSchema().getField(nonDocValuesField).getType() instanceof PointField); minBucketVal = min; for (int i = 0 ; i < numBuckets ; minBucketVal += gap, ++i) { testStrings[i] = "//lst[@name='facet_counts']/lst[@name='facet_ranges']/lst[@name='" + nonDocValuesField + "']/lst[@name='counts']/int[@name='" + minBucketVal + "'][.='" + bucketCount[i] + "']"; } // Range Faceting with method = filter should work assertQ(req("q", "*:*", "facet", "true", "facet.range", nonDocValuesField, "facet.range.start", String.valueOf(min), "facet.range.end", String.valueOf(max), "facet.range.gap", String.valueOf(gap), "facet.range.method", "filter"), testStrings); // this should actually use filter method instead of dv assertQ(req("q", "*:*", "facet", "true", "facet.range", nonDocValuesField, "facet.range.start", String.valueOf(min), "facet.range.end", String.valueOf(max), "facet.range.gap", String.valueOf(gap), "facet.range.method", "dv"), testStrings); }
Example 13
Source File: JsonReader.java From logging-log4j2 with Apache License 2.0 | 4 votes |
private Number readNumber() { // Read sign. buffer.setLength(0); if (readChar == '-') { bufferReadChar(); } // Read fraction. boolean floatingPoint = false; bufferDigits(); if (readChar == '.') { bufferReadChar(); bufferDigits(); floatingPoint = true; } // Read exponent. if (readChar == 'e' || readChar == 'E') { floatingPoint = true; bufferReadChar(); if (readChar == '+' || readChar == '-') { bufferReadChar(); } bufferDigits(); } // Convert the read number. final String string = buffer.toString(); if (floatingPoint) { return new BigDecimal(string); } else { final BigInteger bigInteger = new BigInteger(string); try { return bigInteger.intValueExact(); } catch (ArithmeticException ignoredIntOverflow) { try { return bigInteger.longValueExact(); } catch (ArithmeticException ignoredLongOverflow) { return bigInteger; } } } }
Example 14
Source File: Main.java From Java-Coding-Problems with MIT License | 3 votes |
public static void main(String[] args) { BigInteger nr = BigInteger.valueOf(Long.MAX_VALUE); long nrLong = nr.longValue(); System.out.println(nr + " as long is: " + nrLong); int nrInt = nr.intValue(); System.out.println(nr + " as int is: " + nrInt); short nrShort = nr.shortValue(); System.out.println(nr + " as short is: " + nrShort); byte nrByte = nr.byteValue(); System.out.println(nr + " as byte is: " + nrByte); long nrExactLong = nr.longValueExact(); // ok System.out.println(nr + " as exact long is: " + nrExactLong); int nrExactInt = nr.intValueExact(); // ArithmeticException System.out.println(nr + " as exact int is: " + nrExactInt); short nrExactShort = nr.shortValueExact(); // ArithmeticException System.out.println(nr + " as exact short is: " + nrExactShort); byte nrExactByte = nr.byteValueExact(); // ArithmeticException System.out.println(nr + " as exact byte is: " + nrExactByte); }
Example 15
Source File: IntegerTextField.java From ghidra with Apache License 2.0 | 3 votes |
/** * Returns the current value as a long. * * <P> If the field has no current value, 0 will be returned. If * the value is bigger (or smaller) than an long, it will be cast to a long. * * <P> If using this method, it is highly recommended that you set the max value to {@link Long#MAX_VALUE} * or lower. * * @return the current value as a long. Or 0 if there is no value * @throws ArithmeticException if the value in this field will not fit into a long */ public long getLongValue() { BigInteger currentValue = getValue(); if (currentValue == null) { return 0; } return currentValue.longValueExact(); }