Home > Back-end >  BigInteger in Python?
BigInteger in Python?

Time:05-02

I currently need to write a receiver program in python and i wonder what i am doing wrong. In java i have (code snippets obviously):

    byte[] fileSize = new byte[2];
    BigInteger bi = new BigInteger(fileSize);
    System.out.println("FileSize in Bytes: "   bi);

which gives back the value of: FileSize in Bytes: 27762

If i print out the array byte fileSize, i get the following values back:

for(int u = 0; u < fileSize.length; u  ){

    System.out.println(fileSize[u]);
            
}

this gives back: 108 and the value 114.

I receive those two values on the python side (its sended trough a Datagram to the Python receiver). How do i combine them or transform them into the value 27762 like BigInteger returns in Java? Kinda lost on this.

Any ideas would be great!

Thanks in advance!

CodePudding user response:

TL;DR:

>>> int.from_bytes([108, 114], 'big') # easy way
27762
>>> (108 << 8)   114 # what you are doing under the hood
27762

Long answer:

The operation you are looking for in Python are called bitwise operations.

Essentially you want to pack two values together as binary.

108 in binary is 1101100 114 in binary is 1110010

to pack them together in Python back into their bigInt equivalent, you have to shift the 108 to make space for the 114. You shift it by 8 binary places towards left

108 in binary, shifted 8 places is 110110000000000. Now we pack them together:

 110110000000000
         1110010
----------------
 110110001110010

Converting 110110001110010 back to decimal we get 27762

So in essence the operation you want is:

>>> (108 << 8)   114
27762

You will have to figure out the details yourself for edge cases, like if your numbers require more bytes shifted than just one byte (aka the 8 bits in code 108 << 8)

CodePudding user response:

I was able to fix it, just in case someone runs into the same issue:

In Python:

test = []

test.append(108)
test.append(114)


print(int.from_bytes(test, 'big'))

which gives back the value of 27762, exactly as the BigInteger conversion in Java.

Cheers!

  • Related