Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java and Python return different values when converting the hexadecimal to long

I noticed this difference when comparing xxhash implementations in both Python and Java languages. Calculated hashes by xxhash library is the same as hexadecimal string, but they are different when I try to get calculated hash as an integer(or long) value.

I am sure that this is some kind of "endian" problem but I couldn’t find how to get the same integer values for both languages.

Any ideas how and why this is happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Java Code:

String hexString = "d24ec4f1a98c6e5b";
System.out.println(new BigInteger(hexString,16).longValue());
// printed value -> -3292477735350538661

Python Code:

hexString = "d24ec4f1a98c6e5b"
print(int(hexString, 16))
# printed value -> 15154266338359012955

>Solution :

You converted the BigInteger to long which is the reason for the difference. Because long is a signed 64-bits integer it overflows to a negative. If you just print the BigInteger as it is it gives the same result.

      System.out.println(new BigInteger(hexString,16));
# 15154266338359012955
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading