Recently I have been learning about bitwise operators and along the way there is this code that finds the binary digits of a decimal number using the AND(&) bitwise operator, the code is as follows:
byte b = -34;
for(int t = 128;t > 0; t = t/2)
{
if((b & t) != 0)System.out.println("1 ");
else System.out.println("0 ");
System.out.println("b & t yields: " + (b & t));
}
I have modified the code to show the value calculated by b&t during each iteration. I would like to understand the exact mechanism behind this code as to why it works to find the binary digits, please explain why is b compared to t each iteration and why is t divided by 2 each iteration?
In addition, I would like to know how is (b&t) calculated manually by listing the binary digits.I do have an understanding how & works but when I listed out the binary digits of 34 and 128 and compared them:
1 0 0 0 0 0 0 0(128)
0 0 1 0 0 0 1 0(34) //I am unsure if the negative sign should be included
---------------
0 0 0 0 0 0 0 0
the result I got was 0, however the program returns 128 which is perplexing.
Below I will also include the result of the execution of the program:
1
b & t yields: 128
1
b & t yields: 64
0
b & t yields: 0
1
b & t yields: 16
1
b & t yields: 8
1
b & t yields: 4
1
b & t yields: 2
0
b & t yields: 0
Much obliged for the help :)
-34is represented by256-34as a unsigned byte.