if 语句字节与整数

if statement byte versus integer

我试图理解下面(摘录)中与演示按位运算符相关的一段代码,特别是 if 语句 ((if ((b & t)...)

变量b是byte类型,t是int。我无法确定如何在循环中测试两个不同的变量类型不等于 0。该程序只是继续翻转位。但是,我无法解决这个问题。它在 Eclipse 中运行良好。有什么想法吗?

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 对两个 int 执行按位与运算。 byte b 升级为 int.

它打印 -34.

的二进制表示的位

-34的二进制表示为11011110。

t 得到值 128,64,32,16,8,4,2,1,在二进制中是

10000000
01000000
00100000
00010000
00001000
00000100
00000010
00000001

当您将 t 的这些值与 b 进行位运算时,仅当 tb 具有“1”时,您才会得到非 0 结果位在相同的位置。

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

编辑:这个解释并不完全准确。按位与在两个 int 上执行(即两个 32 位数),但由于 t 的前 24 位是 0,因此它们不会影响结果。