[英]Can someone please explain this bitwise program to me?
public class UpCase {
public static void main(String[] args) {
int t;
byte val;
val = 123;
for (t = 128; t > 0; t = t / 2) {
System.out.println(t);
if ((val & t) != 0) System.out.println(" 1");
else System.out.println(" 0");
}
}
}
In particular, I am not sure why we are using val=123
?特别是,我不确定为什么我们使用
val=123
? I understand that this program will print out 123 in binary but why is that the case?我知道这个程序会以二进制形式打印出 123 但为什么会这样呢? How does this work?
这是如何运作的? I do understand however, the principles of the
&
operator and how you can turn on and off bits but I am not sure how it works in this particular example?但是,我确实理解
&
运算符的原理以及如何打开和关闭位,但我不确定它在此特定示例中的工作原理?
This program will print out the binary digits of the number in val
from MSB to LSB by comparing it to each power of 2:该程序将通过与 2 的每个幂进行比较,将
val
数字的二进制数字从 MSB 打印到 LSB:
123 : 01111011 &
128 : 10000000 =
00000000
00000000 != 0 => false, print 0
123 : 01111011 &
64 : 01000000 =
01000000
01000000 != 0 => true, print 1
123 : 01111011 &
32 : 00100000 =
00100000
00100000 != 0 => true, print 1
// repeat for 2^4-2^1...
123 : 01111011 &
1 : 00000001 =
00000001
00000001 != 0 => true, print 1
Very simple:很简单:
It just checks if the value (123 in this case) using the bitwise operator &.它只是使用按位运算符 & 检查值(在本例中为 123)。 The result of that is 1 or 0, this process is repeated for the following value 0.5t etc until t=0, resulting in the binary string for this value 123.
其结果为 1 或 0,此过程对下一个值 0.5t 重复,直到 t=0,产生此值 123 的二进制字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.