• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

two's complement

 
suresh kamsa
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. byte b1 = (byte)(2 * Byte.MAX_VALUE);
I think b1 = 0111 1111 1111 1111 1111 1111 1111 1111
2.byte b2 = -2;
for negtive number
1000 0000 0000 0000 0000 0000 0000 0000
binary of 2 is 10
which is equal to
1000 0000 0000 0000 0000 0000 0000 0010 if I invert also because of negtive we should get
0111 1111 1111 1111 1111 1111 1111 1101
How is (b1 == b2).Did I do anything wrong?
Thanks.
 
Kavitha Chandrasekaran
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
b1 will be 11111110 and because it is a byte, it has 8 bits with the most significant bit as 1(that makes it negative). When you do the conversion to decimal,the value is -2.
So, b1 == b2 is true.
Kavitha
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A byte is only 8 bits, not 32 as you are showing here.
 
suresh kamsa
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. byte b1 = (byte)(2 * Byte.MAX_VALUE);
2. byte b2 = -2;
3. System.out.println(b1 == b2);
as per my knowledge MAX_VALUE = 0111 ... 1111
according to that b1 = 0111 1111(most significant seven bits set to 1 and least one bit set to zero)
MIN_VALUE = 1000 ... 0000
how b1 becomes -2 here, please explain me in detail.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you said Byte.MAX_VALUE is 01111111. Now, when you multiply a number by 2, what happens is a shift left by one bit. So,
Byte.MAX_VALUE * 2
can be resolved to
01111111 << 1
which gives
11111110
whose value is -2.
To be sure, let's take the byte value 2 and make it negative (keyword: 2's complement):
2 is 00000010
to get -2 we invert all bits like this
11111101
and add 1, that is
11111110
As you can see we get the same value...
So Byte.MAX_VALUE * 2 is equal to -2
 
suresh kamsa
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your in-detail explanation.
Is the same rule applies wheh I multiply number by 3 or 4 etc.(shift left by one bit)
eg.(Byte.MAX_VALUE * 3)
Is the same rule applies to Short.MAXVALUE,Integer.MAXVALUE etc. If anybody has a chart kind which shows this please pass on to me.
What about Byte.MINVALUE,Short.MINVALUE,Integer.MINVALUE etc
Is this possible only for Wrapper primitives?
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic