java - Why Integer.toBinaryString returns 32 bits if the argument is negative? -


i messing around integer.tobinarystring(int) method.

when pass positive number 7, outputs 111 when pass negative 7, outputs 11111111111111111111111111111001. understand java uses 2's complement represent negative numbers, why 32 bits (i know int 32 bits long doesn't fit in answer)?

ok did digging...

i wrote little program close did.

public class inttest {     public static void main(string[] args){         int = 7;         int b = -7;         system.out.println(integer.tobinarystring(a));         system.out.println(integer.tobinarystring(b));     } } 

my output:

111

11111111111111111111111111111001

so 111 same if had 29 "0"s in front of it. wasted space , time.

if follow instructions twos compliment guy here can see must flip bits ( zeros become ones , ones become zeros ) add 1 result.

so 0000 0000 0000 0000 0000 0000 0000 0111 becomes 1111 1111 1111 1111 1111 1111 1111 1001

the ones can not thrown out because significant in twos compliment representation. why have 32 bits in second case.

hope helps! -- code on!!!


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -