有人可以向我解释这个按位程序吗?

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");
        }
    }
}

特别是,我不确定我们为什么要使用 val=123?我知道这个程序会以二进制形式打印出 123,但为什么会这样呢?这是如何运作的?不过,我确实理解 & 运算符的原理以及如何打开和关闭位,但我不确定它在这个特定示例中是如何工作的?

很简单:

它只是检查值(在本例中为 123)是否使用按位运算符 &。结果为 1 或 0,对以下值 0.5t 等重复此过程,直到 t=0,从而产生此值 123 的二进制字符串。

此程序将通过将 val 中的数字与 2 的每个幂进行比较,从 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