Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bytes to integer in Java vs Python

Tags:

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?

like image 457
ThanosFisherman Avatar asked Apr 15 '16 03:04

ThanosFisherman


1 Answers

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
like image 166
user2357112 supports Monica Avatar answered Sep 28 '22 04:09

user2357112 supports Monica