Skip to content

Parsing string long to int with java and python

I am trying to convert some java code to python. I have a problem with the following java lines :

int toto = (int)Long.parseLong("11101101111110100111001110011010",2);
String result = Integer.reverseBytes(toto);

In java, i get those results :

Long.parseLong("11101101111110100111001110011010",2) = 3992613786
(int)Long.parseLong("11101101111110100111001110011010",2) = -302353510
Integer.reverseBytes(toto) = -1703675155

I think I understand the first line, but why is there a “(int)” here ? What is it supposed to do ? (I’m a beginner in java and in byte management, and I couldn’t find any documentation that I understand regarding that point).

In python, I managed to get the first result by converting to base 2 (I found this out totally by chance) :

int("11101101111110100111001110011010",2) = 3992613786

But how can I obtain the “int” result, and then the “reverse byte” result in python ?

(By the way, I use Python 3)



In the end, I used the answer from gengkev here.

By playing around, I found something similar to BreizhGatch’s function, but that doesn’t require a conditional statement. n & 0x80000000 extracts the 32-bit sign bit; then, the – keeps the same 32-bit representation but sign-extends it; finally, the extended sign bits are set on n.

def toSigned32(n):

n = n & 0xffffffff return n | (-(n & 0x80000000))

1 People found this is helpful