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

The following examples show how to use java.math.BigInteger#longValue() . 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: nuls   File: Utils.java    License: MIT License 6 votes vote down vote up
/**
 * @see Utils#decodeCompactBits(long)
 */
public static long encodeCompactBits(BigInteger value) {
    long result;
    int size = value.toByteArray().length;
    if (size <= 3)
        result = value.longValue() << 8 * (3 - size);
    else
        result = value.shiftRight(8 * (size - 3)).longValue();
    // The 0x00800000 bit denotes the sign.
    // Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
    if ((result & 0x00800000L) != 0) {
        result >>= 8;
        size++;
    }
    result |= size << 24;
    result |= value.signum() == -1 ? 0x00800000 : 0;
    return result;
}
 
Example 2
Source Project: ghidra   File: NSObject.java    License: Apache License 2.0 6 votes vote down vote up
protected long getValue( Data component ) {
		try {
			byte [] bytes = component.getBytes( );
//			if ( bytes.length == 1 ) {
//				return bytes[ 0 ] & 0xffL;
//			}
//			else if ( bytes.length == 2 ) {
//				return converter.getShort( bytes ) & 0xffffL;
//			}
//			else if ( bytes.length == 4 ) {
//				return converter.getInt( bytes ) & 0xffffffffL;
//			}
//			else if ( bytes.length == 8 ) {
//				return converter.getLong( bytes );
//			}
//			else {
//				
//			}
			BigInteger bi = new BigInteger( bytes );
			return bi.longValue( );
		}
		catch ( MemoryAccessException e ) {

		}
		return -1;
	}
 
Example 3
Source Project: SPADE   File: Audit.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Converts syscall args: 'a0', 'a1', 'a2', and 'a3' from hexadecimal values to decimal values
 * 
 * Conversion done based on the length of the hex value string. If length <= 8 then integer else a long.
 * If length > 16 then truncated to long.
 * 
 * Done so to avoid the issue of incorrectly fitting a small negative (i.e. int) value into a big (i.e. long) value
 * causing a wrong interpretation of bits.
 * 
 * @param eventData map that contains the above-mentioned args keys and values
 * @param time time of the event
 * @param eventId id of the event
 * @param syscall syscall of the event
 */
private void convertArgsHexToDec(Map<String, String> eventData, String time, String eventId, SYSCALL syscall){
	String[] argKeys = {AuditEventReader.ARG0, AuditEventReader.ARG1, AuditEventReader.ARG2, AuditEventReader.ARG3};
	for(String argKey : argKeys){
		String hexArgValue = eventData.get(argKey);
		if(hexArgValue != null){
			int hexArgValueLength = hexArgValue.length();
			try{
				BigInteger bigInt = new BigInteger(hexArgValue, 16);
				String argValueString = null;
				if(hexArgValueLength <= 8){
					int argInt = bigInt.intValue();
					argValueString = Integer.toString(argInt);
				}else{ // greater than 8
					if(hexArgValueLength > 16){
						log(Level.SEVERE, "Truncated value for '" + argKey + "': '"+hexArgValue+"'. Too big for 'long' datatype", null, time, eventId, syscall);
					}
					long argLong = bigInt.longValue();
					argValueString = Long.toString(argLong);
				}
				eventData.put(argKey, argValueString);
			}catch(Exception e){
				log(Level.SEVERE, "Non-numerical value for '" + argKey + "': '"+hexArgValue+"'", e, time, eventId, syscall);
			}
		}else{
			log(Level.SEVERE, "NULL value for '" + argKey + "'", null, time, eventId, syscall);
		}
	}
}
 
Example 4
Source Project: graphql-jpa   File: JavaScalars.java    License: MIT License 5 votes vote down vote up
@Override
public Object parseLiteral(Object input) {
    if (input instanceof StringValue) {
        return parseStringToDate(((StringValue) input).getValue());
    } else if (input instanceof IntValue) {
        BigInteger value = ((IntValue) input).getValue();
        return new Date(value.longValue());
    }
    return null;
}
 
Example 5
private Integer extractChainIdFromV(BigInteger bv) {
  if (bv.bitLength() > 31) {
    return Integer.MAX_VALUE; // chainId is limited to 31 bits, longer are not valid for now
  }
  long v = bv.longValue();
  if (v == LOWER_REAL_V || v == (LOWER_REAL_V + 1)) return null;
  return (int) ((v - CHAIN_ID_INC) / 2);
}
 
Example 6
@Override
public void initModules() {
	try {
		for (String line : Files.readAllLines(Paths.get("/proc/" + id() + "/maps"))) {
			String[] split = line.split(" ");
			String[] regionSplit = split[0].split("-");
			
			BigInteger start = new BigInteger(regionSplit[0], 16);
			BigInteger end = new BigInteger(regionSplit[1], 16);
			BigInteger offset = new BigInteger(split[2], 16);
			
			if (offset.longValue() <= 0 || start.compareTo(LONG_MAX_VALUE) > 0 || end.compareTo(LONG_MAX_VALUE) > 0) {
				continue;
			}
			
			StringBuilder path = new StringBuilder();
			
			for (int i = 5; i < split.length; i++) {
				String s = split[i].trim();
				if (!s.isEmpty()) {
					path.append(split[i]);
				}
				if (s.isEmpty() && ++i > split.length) {
					break;
				} else if (s.isEmpty() && !split[i].trim().isEmpty()) {
					path.append(split[i]);
				}
			}
			
			String modulename = path.substring(path.lastIndexOf("/") + 1);
			modules.put(modulename, new Module(this, modulename, Pointer.createConstant(start.longValue()), end.longValue() - start.longValue()));
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 7
Source Project: joshua   File: BloomFilter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds a prime number that is larger than the given number. This is used to find bigPrime, a
 * prime that has to be larger than the size of the Bloom filter.
 * 
 * @param n an integer
 * 
 * @return a prime number larger than n
 */
private long getPrimeLargerThan(int n) {
  BigInteger ret;
  BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE);
  int numBits = BigInteger.valueOf(n).bitLength() + 1;
  do {
    ret = BigInteger.probablePrime(numBits, RANDOM);
  } while (ret.compareTo(maxLong) > 1);
  return ret.longValue();
}
 
Example 8
public static long longValueExact(BigInteger bigInt)
{
    if (bigInt.bitLength() >= Long.SIZE)
    {
        throw new ArithmeticException("Input value for conversion is not within the range of data type long");
    }
    return bigInt.longValue();
}
 
Example 9
public long calculate_fee(fee_parameters_type feeParametersType) {
    long lFee = feeParametersType.fee;
    if (memo != null) {
        // 计算数据价格
        Gson gson = global_config_object.getInstance().getGsonBuilder().create();
        BigInteger nSize = BigInteger.valueOf(gson.toJson(memo).length());
        BigInteger nPrice = BigInteger.valueOf(feeParametersType.price_per_kbyte);
        BigInteger nKbyte = BigInteger.valueOf(1024);
        BigInteger nAmount = nPrice.multiply(nSize).divide(nKbyte);

        lFee += nAmount.longValue();
    }

    return lFee;
}
 
Example 10
@Override
public Long createFromBigInteger(BigInteger i) {
    return i.longValue();
}
 
Example 11
Source Project: tutorials   File: TextSearchAlgorithms.java    License: MIT License 4 votes vote down vote up
public static long getBiggerPrime(int m) {
    BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
    return prime.longValue();
}
 
Example 12
Source Project: CPUSim   File: Arithmetic.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * execute the micro instruction from machine
 */
public void execute()
{
    long value1 = source1.get().getValue();
    long value2 = source2.get().getValue();
    BigInteger op1 = BigInteger.valueOf(value1);
    BigInteger op2 = BigInteger.valueOf(value2);
    int width = destination.get().getWidth();
    BigInteger twoToWidthMinusOne = BigInteger.valueOf(2).pow(width-1);
    BigInteger result = null;

    if (type.get().equals("ADD"))
        result = op1.add(op2);
    else if (type.get().equals("SUBTRACT"))
        result = op1.subtract(op2);
    else if (type.get().equals("MULTIPLY"))
        result = op1.multiply(op2);
    else if (type.get().equals("DIVIDE"))
        if (op2.compareTo(BigInteger.ZERO) == 0)
            throw new ExecutionException("There was an " +
                    "attempt to divide by 0.");
        else
            result = op1.divide(op2);

    //set overflow bit if necessary
    if (result.compareTo(twoToWidthMinusOne) >= 0 ||
            result.compareTo(twoToWidthMinusOne.negate()) < 0)
        overflowBit.get().set(1);
    else
        overflowBit.get().set(0);

    //set the carry bit if necessary
    if (type.get().equals("ADD") &&
            ((value1 < 0 && value2 < 0) ||
                    (value1 < 0 && value2 >= -value1) ||
                    (value2 < 0 && value1 >= -value2)))
        carryBit.get().set(1);
    else
        carryBit.get().set(0);

    //save the result
    long longResult = result.longValue();
    destination.get().setValue((longResult << (64 - width)) >> (64 - width));
}
 
Example 13
Source Project: jigsaw-payment   File: JavaPropsFormat.java    License: Apache License 2.0 4 votes vote down vote up
private static long parseInteger(final String text,
                                 final boolean isSigned,
                                 final 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;
  }

  final 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.longValue();
  }

  return result;
}
 
Example 14
@Override
public boolean check(XCO xco, String fieldName, Object value) {
	BigInteger val = xco.getBigIntegerValue(fieldName);
	BigInteger[] result = (BigInteger[]) value;
	return val.longValue() >= result[0].longValue() && val.longValue() <= result[1].longValue();
}
 
Example 15
Source Project: aion   File: Statefulness.java    License: MIT License 4 votes vote down vote up
public static long getBalanceOf(Address address) {
    BigInteger balance = Blockchain.getBalance(address);
    Blockchain.println("Balance of " + address + " = " + balance);
    counter++;
    return balance.longValue();
}
 
Example 16
Source Project: krpc   File: BeanToMessage.java    License: Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, Descriptors.FieldDescriptor field, boolean isRepeated) {

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                return TypeSafe.anyToInt(value);

            case INT64:
            case SINT64:
            case SFIXED64:
                if( value instanceof Date)
                    return ((Date)value).getTime();
                return TypeSafe.anyToLong(value);

            case BOOL:
                return TypeSafe.anyToBool(value);

            case FLOAT:
                return TypeSafe.anyToFloat(value);

            case DOUBLE:
                return TypeSafe.anyToDouble(value);

            case UINT32:
            case FIXED32:
                return (int) (TypeSafe.anyToLong(value) & 0x00000000FFFFFFFFL);

            case UINT64:
            case FIXED64:
                BigInteger bi = new BigInteger(value.toString());
                return bi.longValue();

            case STRING:
                if( value instanceof Date)
                    return formatDate((Date)value);
                return TypeSafe.anyToString(value);

            case BYTES: {
                if (value instanceof ByteString) {
                    return value;
                }
                if (value instanceof String) {
                    byte[] bb = getBytes((String) value);
                    if (bb == null) return null;
                    return ByteString.copyFrom(bb);
                }
                if (value instanceof byte[]) {
                    return ByteString.copyFrom((byte[]) value);
                }
            }

            return null;

            case ENUM:
                Descriptors.EnumDescriptor ed = field.getEnumType();
                Descriptors.EnumValueDescriptor evd = ed.findValueByName(value.toString());
                if (evd == null) {
                    evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                }
                if (evd == null) return null;
                return evd;

            case MESSAGE:

                Object bean = value;

                Builder b2 = isRepeated ?
                        getRepeatedFieldBuilder(b, field.getName()) :
                        getFieldBuilder(b, field);

                for (Descriptors.FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(bean, subName);
                    if (subValue == null) continue;
                    if (subfield.isRepeated()) {
                        objToMessageObjRepeated(b2, subValue, subfield);
                    } else {
                        objToMessageObj(b2, subValue, subfield);
                    }
                }

                return isRepeated ? null : b2.build();

            default:
                return null;
        }
    }
 
Example 17
/**
 * Increment the memcache version of the named-counter by {@code amount} (positive or negative) in an atomic
 * fashion. Use memcache as a Semaphore/Mutex, and retry up to 10 times if other threads are attempting to update
 * memcache at the same time. If nothing is in Memcache when this function is called, then do nothing because only
 * #getCounter should "put" a value to memcache. Additionally, if this operation fails, the cache will be
 * re-populated after a configurable amount of time, so the count will eventually become correct.
 *
 * @param counterName
 * @param amount
 * @return The new count of this counter as reflected by memcache
 */
@VisibleForTesting
protected Optional<Long> incrementMemcacheAtomic(final String counterName, final long amount)
{
	Preconditions.checkNotNull(counterName);

	// Get the cache counter at a current point in time.
	String memCacheKey = this.assembleCounterKeyforMemcache(counterName);

	for (int currentRetry = 0; currentRetry < NUM_RETRIES_LIMIT; currentRetry++)
	{
		try
		{
			final IdentifiableValue identifiableCounter = memcacheService.getIdentifiable(memCacheKey);
			// See Javadoc about a null identifiableCounter. If it's null, then the named counter doesn't exist in
			// memcache.
			if (identifiableCounter == null
				|| (identifiableCounter != null && identifiableCounter.getValue() == null))
			{
				final String msg = "No identifiableCounter was found in Memcache.  Unable to Atomically increment for CounterName '%s'.  Memcache will be populated on the next called to getCounter()!";
				logger.log(Level.FINEST, String.format(msg, counterName));

				// This will return an absent value. Only #getCounter should "put" a value to memcache.
				break;
			}

			// If we get here, the count exists in memcache, so it can be atomically incremented/decremented.
			final BigInteger cachedCounterAmount = (BigInteger) identifiableCounter.getValue();
			final long newMemcacheAmount = cachedCounterAmount.longValue() + amount;

			logger.log(Level.FINEST, String.format("Just before Atomic Increment of %s, Memcache has value: %s",
				amount, identifiableCounter.getValue()));

			if (memcacheService.putIfUntouched(counterName, identifiableCounter,
				BigInteger.valueOf(newMemcacheAmount), config.getDefaultCounterCountExpiration()))
			{
				logger.log(Level.FINEST,
					String.format("MemcacheService.putIfUntouched SUCCESS! with value: %s", newMemcacheAmount));

				// If we get here, the put succeeded...
				return Optional.of(new Long(newMemcacheAmount));
			}
			else
			{
				logger.log(Level.WARNING,
					String.format("Unable to update memcache counter atomically.  Retrying %s more times...",
						(NUM_RETRIES_LIMIT - currentRetry)));
				continue;
			}
		}
		catch (MemcacheServiceException mse)
		{
			// Check and post-decrement the numRetries counter in one step
			if ((currentRetry + 1) < NUM_RETRIES_LIMIT)
			{
				logger.log(Level.WARNING,
					String.format("Unable to update memcache counter atomically.  Retrying %s more times...",
						(NUM_RETRIES_LIMIT - currentRetry)));

				// Keep trying...
				continue;
			}
			else
			{
				// Evict the counter here, and let the next call to getCounter populate memcache
				final String logMessage = "Unable to update memcache counter atomically, with no more allowed retries.  Evicting counter named '%s' from the cache!";
				logger.log(Level.SEVERE, String.format(logMessage, (NUM_RETRIES_LIMIT - currentRetry)), mse);

				this.memcacheSafeDelete(memCacheKey);
				break;
			}
		}
	}

	// The increment did not work...
	return Optional.absent();
}
 
Example 18
Source Project: travelguide   File: TextFormat.java    License: Apache License 2.0 4 votes vote down vote up
private static long parseInteger(final String text,
                                 final boolean isSigned,
                                 final 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;
  }

  final 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.longValue();
  }

  return result;
}
 
Example 19
/**
 * Check if the value is less than or equal to a maximum.
 *
 * @param value The value validation is being performed on.
 * @param max The maximum value.
 * @return <code>true</code> if the value is less than
 *         or equal to the maximum.
 */
public boolean maxValue(BigInteger value, long max) {
    return (value.longValue() <= max);
}
 
Example 20
/**
 * Check if the value is greater than or equal to a minimum.
 *
 * @param value The value validation is being performed on.
 * @param min The minimum value.
 * @return <code>true</code> if the value is greater than
 *         or equal to the minimum.
 */
public boolean minValue(BigInteger value, long min) {
    return (value.longValue() >= min);
}