I am trying to understand a section of code below (excerpt) related to demonstrating bitwise operators, in particular the if
statement ((if ((b & t)...)
The variable b
is of the byte type and the t
int. I cannot determine how two different variable types are tested to not equal 0 in the loop. The program just goes on to flip the bits. However, I cannot get past this issue. It runs fine in Eclipse. Any ideas?
class NotDemo {
public static void main(String args []) {
byte b = -34;
for (int t=128; t > 0; t = t/2 ) {
if((b & t) != 0) System.out.print("1 ");
else System.out.print("0 ");
b & t
performs bit-wise AND on two int
s. The byte
b
is promoted to an int
.
It prints the bits of the binary representation of -34
.
The binary representation of -34 is 11011110.
t
gets the values 128,64,32,16,8,4,2,1, which in binary are
10000000
01000000
00100000
00010000
00001000
00000100
00000010
00000001
When you bit-wise AND these values of t
with b
, you get a non 0 result only when t
and b
have a '1' bit in the same position.
10000000 & 11011110 = 10000000 -> 1 printed
01000000 & 11011110 = 01000000 -> 1 printed
00100000 & 11011110 = 00000000 -> 0 printed
00010000 & 11011110 = 00010000 -> 1 printed
00001000 & 11011110 = 00001000 -> 1 printed
00000100 & 11011110 = 00000100 -> 1 printed
00000010 & 11011110 = 00000010 -> 1 printed
00000001 & 11011110 = 00000000 -> 0 printed
EDIT: this explanation is not completely accurate. The bit-wise AND is performed on two int
s (i.e. two 32 bit numbers), but since the top 24 bits of t
are 0
, they don't affect the result.