Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a negative integer into two's complement binary form? (Java)

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

like image 315
jbreed Avatar asked Apr 23 '11 03:04

jbreed


1 Answers

Integer.toBinaryString works for negatives too. :-) For example, Integer.toBinaryString(-2) returns 11111111111111111111111111111110.

If you take the rightmost 12 characters, you have the bottom 12 bits, as required.

like image 136
Chris Jester-Young Avatar answered Sep 20 '22 23:09

Chris Jester-Young