二进制表示中的所有

All ones in binary representation

我正在浏览 Cracking the coding interview 一书中的一些例子。在位操作章节中,作者使用以下内容创建了一个全一的二进制表示

int allOnes = ~0;

我只是想知道,为什么我们不能简单地做

int allOnes = -1;

可以。试试看吧

System.out.println(Integer.toBinaryString(-1));
System.out.println(Integer.toBinaryString(~0));
System.out.println(~0);

输出是(你可能已经猜到了)

11111111111111111111111111111111
11111111111111111111111111111111
-1

因为~0-1JLS-15.15.5. Bitwise Complement Operator ~ 说(部分),

At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand. In all cases, ~x equals (-x)-1.