Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to BigInteger

Tags:

java

I am trying to convert hex to Big Integer. Basically I have 32 characters = 16 bytes, so I expect that BigInteger also has 16 bytes, but for some cases, i.e. hex starts with 99.. it generates additional byte with 0. I'm using

new BigInteger(hex, 16)

How can I avoid the 17th byte?

like image 607
berry_burr Avatar asked Mar 24 '26 03:03

berry_burr


2 Answers

From BigInteger's javadoc :

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types).

And description of the constructor you are using :

Translates the String representation of a BigInteger in the specified radix into a BigInteger. The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).

This means that if you call it with new BigInteger( "99000000000000000000000000000000", 16) you will get a BigInteger which holds that value (which is a positive value) as if it were represented in two's-complement notation. That positive value in two's complement does not fit in 16 bytes so of course the end result is 17 bytes long.

You are guaranteed to get a BigInteger with a maximun of 16 bytes if you call it with values between (both included):

 - new BigInteger( "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16)
 - new BigInteger("-80000000000000000000000000000000", 16)

Any value higher than the first or lower than the last will result in more than 16 bytes.

like image 145
Anonymous Coward Avatar answered Mar 26 '26 17:03

Anonymous Coward


The first byte cannot start with an 1 bit, because that would mean a negative number. They prevent this by adding an additional zero byte at the start of the array. This function will check and chop off that byte:

public static byte[] signedToUnsignedBytes(byte[] myBytes) {
    return myBytes.length > 1 && myBytes[0] == 0
        ? Arrays.copyOfRange(myBytes, 1, myBytes.length)
        : myBytes;
}
like image 28
Tamas Hegedus Avatar answered Mar 26 '26 15:03

Tamas Hegedus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!