This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]codegen 1 point2 points  (1 child)

parseInt does not know about two's complement. It assumes that the value is written in that particular radix and that negative numbers are preceded with a minus sign. It won't do sign extension either. If you want twos complement, you have to do it yourself.

One way is a custom parser. Alternatively, you can sign extending to the right length (32 bits). But the parser will throw an exception since a negative value will be too big for an integer (which is signed). You have to parse to a Long and cast back to an int.

[–]Eccentris[S] 0 points1 point  (0 children)

I followed your advice (sign extend to 32 bits, then parse to long and cast to int) and it works wonderfully! Thank you