5

I have the following code in python:

    myBytes = m.digest()
    for one in myBytes:
        print(one, end=' ')
    print(end='\n')
    intlist = int.from_bytes(myBytes, 'little')
    print("intlist", intlist)

the above code prints the following result

72 230 166 56 69 98 5 189 49 43 129 54 237 2 147 230

intlist 306485766027497339553611008967975560776

Now I want to achieve the exact same result in java. This is my code so far:

byte[] myBytes = md.digest();
System.out.println(Arrays.toString(myBytes));
BigInteger intlist = new BigInteger(myBytes);
System.out.println("intlist=" + intlist);

and the result I get from this is the following:

[72, -26, -90, 56, 69, 98, 5, -67, 49, 43, -127, 54, -19, 2, -109, -26]

intlist=96902015312221227689534558263304164326

The result in java is wrong for what I want to do. I want to get the exact same values as on python code.

Any ideas?

1
  • Have you checked byte order? Java is Big Endian by default Commented Apr 15, 2016 at 3:15

1 Answer 1

4

You've specified little-endian byte order in Python:

intlist = int.from_bytes(myBytes, 'little')

but the Java BigInteger(byte[] val) constructor takes input in big-endian order. Also, int.from_bytes defaults to assuming the input represents an unsigned integer, while BigInteger(byte[] val) interprets its input as a two's-complement signed integer.

If you want to replicate the Python result in Java, reverse the order of the array and use the sign/magnitude BigInteger(int signum, byte[] magnitude) constructor to treat the array as representing a positive number:

byte[] bytes = {72, -26, -90, 56, 69, 98, 5, -67, 49, 43, -127, 54, -19, 2, -109, -26};
for (int i = 0; i < bytes.length / 2; i++) {
    byte temp = bytes[i];
    bytes[i] = bytes[bytes.length - i - 1];
    bytes[bytes.length - i - 1] = temp;
}
System.out.println(new BigInteger(1, bytes));

Output:

306485766027497339553611008967975560776
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That was exactly what I needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.