我试图理解下面一段代码(摘录)与演示按位运算符相关,特别是 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
进行位运算时,只有当 t
和 时才会得到非 0 结果b
在同一位置有一个“1”位。
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
, 它们不会影响结果。
关于java - if 语句字节与整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53848105/