xarax said:
I was using Long.toHexString() and Long.parseLong() for dealing
with 64-bit integers. I now need to handle 128-bit integers, so
I looked at java.math.BigInteger, but it doesn't have hexadecimal
(or any base conversion/formatting) methods.
How should I parse "0xa9ce09230dea0b9032340ade9034d334" into
a BigInteger?
You need a method to convert the hex string to an integer string, or a
byte array. Then pass that to the BigInteger constructor.
Here is a small method to convert a hex String to a byte array. This
method doesn't use the 0x prefix, and it assumes that the String is of
even length (you can't convert f, instead you must use 0f). Also,
remember that you need to use the BigInteger(int signum, byte[]
magnitude) constructor with signum = 1.
static byte[] stringToBytes(CharSequence str)
{
int len = str.length();
if (len % 2 != 0)
{
throw new IllegalArgumentException("Sequence length not even: " + len);
}
byte[] b = new byte[len / 2];
for (int i = len - 1; i > 0; i -= 2)
{
char c = str.charAt(i);
int bt = 0;
// 0-9
if (c >= 0x30 && c <= 0x39)
{
bt += c - 0x30;
}
// A-F (uppercase)
else if (c >= 0x41 && c <= 0x46)
{
bt += c - 0x37;
}
// a-f (lowercase)
else if (c >= 0x61 && c <= 0x66)
{
bt += c - 0x57;
}
else
{
throw new IllegalArgumentException("Not a hex value: " + c + " at
position: " + i);
}
char cNext = str.charAt(i - 1);
if (cNext >= 0x30 && cNext <= 0x39)
{
bt += (cNext - 0x30) * 16;
}
else if (cNext >= 0x41 && cNext <= 0x46)
{
bt += (cNext - 0x37) * 16;
}
else if (cNext >= 0x61 && cNext <= 0x66)
{
bt += (cNext - 0x57) * 16;
}
else
{
throw new IllegalArgumentException("Not a hex value: " + c + " at
position: " + (i - 1));
}
b[i / 2] = (byte) bt;
}
return b;
}
How should I get a BigInteger as a hexadecimal
string?
The reverse of above.