Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# simple Bitwise

Greenhorn

Joined: Mar 05, 2001
Posts: 29
What does the following code print out?
byte b1 = -5;
int i = 0xff;
byte b2 = (byte)(b1 ^ i);
System.out.println(b2);
Can someone explain why it is 4? Thanks!
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4243

2

1. binary for -5 is 11111011 (8 bits only since it's a byte)
2. binary for 0xff is 00000000 00000000 00000000 11111111 (ints have 32 bits)
3. the byte is promoted to int, giving you 32 bits
00000000 00000000 00000000 11111011 // -5 promoted to int
4. ^ (xor) operator applied
00000000 00000000 00000000 11111011
00000000 00000000 00000000 11111111
------------------------------------
00000000 00000000 00000000 00000100
Based on the following truth table:
 op1 op2 (op1 ^ op2) --- --- ----------- 0 0 0 0 1 1 1 0 1 1 1 0

5. result of step 4 is cast to byte, leaving only the 8 rightmost bits: 00000100 (4 decimal)
6. println() outputs numeric values in decimal.
J.Lacar
(tried to eliminate space before the truth table but couldn't)

[This message has been edited by JUNILU LACAR (edited March 10, 2001).]

Greenhorn

Joined: Mar 05, 2001
Posts: 29
Thanks JUNILU!
niraj singh
Ranch Hand

Joined: Feb 07, 2001
Posts: 36
Hi Junilu,
I think there is one small thing which was wrong in your answer.
When a byte is promoted to an int, and the exteme left digit of the byte is a 1 (which would indicate it is a negative number), the rest of the increased bytes will also be filled with 1's. so,
So, byte -5 = 11111011
but int -5 = 11111111 11111111 11111111 11111011
and not 00000000 00000000 00000000 11111011 as mentioned by you.
This can be checked by the same code above. If we change the
code to -

When we are casting the XOR'd value from int to byte, we are losing the 3 extereme left bytes. But, as per your answer, if the extreme left 3 bytes contain only zero's, then the answer
should not make any difference whether it is a int or a byte.
The actual answer will be as follows -
11111111 11111111 11111111 11111011 //byte -5 after promotion
00000000 00000000 00000000 11111111 //int 0xff
-----------------------------------
11111111 11111111 11111111 00000100 //XOR'd int value = -252
0000100 //casted to byte = 4
Hope that helps
Niraj

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

subject: simple Bitwise