How to convert a negative integer to binary binary form? (Java)

I need to convert numbers, positive and negative, to binary format - like this, 2 in "00000010" and -2 in "11111110", for example. I don't need more than 12 bits or so, so if the string is longer than I can just truncate the leading signed bits. It seems that it Integer.toBinaryString()will do positive numbers, but is there one that can do negatives?

+5
source share
1 answer

Integer.toBinaryStringalso works for negatives. :-) For example, Integer.toBinaryString(-2)returns 1111111111111111111111111111111110.

If you take the last 12 characters, you have the bottom 12 bits if required.

+10

All Articles