Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Java Interview Guide this week in the Jobs Discussion forum!

# two's complement

suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
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

Joined: Jul 24, 2002
Posts: 34
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

Joined: Jun 06, 2002
Posts: 1056
A byte is only 8 bits, not 32 as you are showing here.

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
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

Joined: Aug 26, 2001
Posts: 7610
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
11111110
As you can see we get the same value...
So Byte.MAX_VALUE * 2 is equal to -2

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
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.
Is this possible only for Wrapper primitives?
Thanks

I agree. Here's the link: http://aspose.com/file-tools

subject: two's complement