I try to convert byte[] to long, but I got java.lang.NumberFormatException.
this is the byte array I wanna convert to long
byte[] data = new byte[]{(byte) 0xDB, (byte) 0xA7, 0x53, (byte) 0xF8, (byte) 0xA8, 0x0C, 0x66, 0x8};
Then I try to convert that data to hex string with this algorithm
public static String hexStringFromHexData(byte[] data){
StringBuilder hexString = new StringBuilder();
for (byte subData : data) {
String temp = Integer.toHexString(subData & 0xFF);
if (temp.length() == 1) {
temp = "0" + temp;
}
hexString.append(temp);
}
return hexString.toString();
}
So I got the hexstring like this "dba753f8a80c6608"
with that hexstring I convert it to long like below
String hexstring = "dba753f8a80c6608";
Long value = Long.parseLong(hexString.trim(), 16);
It throw NumberFormatException because the hexstring is exceed 7fffffffffffffff (Long.MAX_VALUE).
The right hexstring have to be like this "DBA753F8A80C668" and with this hexstring is able to convert it to this long value 989231983928329832L without get exception.
we can try convert this long value back to hex string
long value = 989231983928329832L
String hexString = Long.toHexString(value);
the we got the hexstring like this "DBA753F8A80C668" and if we convert it to byte array it will be same with byte array data like above.
So how do I convert the byte[] data above to hex string like this "DBA753F8A80C668"?
Is it any other algorithm for convert byte[] data above and return correct long value like this 989231983928329832L?
======================================================================
simple step to reproduce:
989231983928329832 to convert it to byte[] data
convert byte[] data back to long value 989231983928329832L