开发者

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

开发者 https://www.devze.com 2023-02-28 10:11 出处:网络
I need to convert numbers, positive and negative, into binary format - so, 2 into \"00000010\", and -2 into \"11111110\", for ex开发者_Python百科ample. I don\'t need more than 12 bits or so, so if the

I need to convert numbers, positive and negative, into binary format - so, 2 into "00000010", and -2 into "11111110", for ex开发者_Python百科ample. 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消