为什么JAVA中与byte按位AND会这样做?

Zim*_*Zim 3 java byte bit-manipulation char bit

我正在摆弄按位运算符,我试图将负字节转换为无符号 8 位值,这就是人们的建议:

System.out.println(-20 & 0xFF); //bitwise AND on negative number and 255 
Run Code Online (Sandbox Code Playgroud)

所以,这工作得很完美,并返回 236,但为什么呢?就我而言:

00010100 //binary representation of -20
11111111 //binary representation of 0xFF or 255
--------
00010100 //it returns the same exact thing, so it's either -20 or 20
Run Code Online (Sandbox Code Playgroud)

为什么它有效?我想我错过了一些非常简单的事情,但我似乎无法理解它。

另外,如果我使用低于 256 的正数,它会返回相同的数字。我似乎无法理解 Java 如何处理这些数字。

Rah*_*ate 5

Java 中的文字采用int. 所以当你说 时-20 & 0xFF,就会发生这样的情况:

  11111111 11111111 11111111 11101100 //-20 -ve nos are stored in 2's compliment form
& 00000000 00000000 00000000 11111111 // 0xFF 
  -------- -------- -------- --------
  00000000 00000000 00000000 11101100 // 236
Run Code Online (Sandbox Code Playgroud)

由于负值以 2 的补码形式存储,因此您得到值 236。

当你执行 时20 & 0xFF,会发生这种情况:

  00000000 00000000 00000000 00010100 // 20 -ve nos are stored in 2's compliment form
& 00000000 00000000 00000000 11111111 // 0xFF 
  -------- -------- -------- --------
  00000000 00000000 00000000 00010100 // 20
Run Code Online (Sandbox Code Playgroud)