如您所知,二进制文字是Java 7中引入的新功能:
int x = 0b1011;
System.out.println(x); // prints 11 as expected
Run Code Online (Sandbox Code Playgroud)
但是,当我试图从文字二进制文件中获取最大数量时,我得到了-1!
int x = 0b11111111111111111111111111111111;
System.out.println(x); // prints -1 !!!
Run Code Online (Sandbox Code Playgroud)
更多详情:
System.out.println(Integer.MAX_VALUE);
System.out.println(0b1111111111111111111111111111111); // 31 bits
/* Both print 2147483647 */
/************************************************************************************/
System.out.println(Integer.MIN_VALUE);
System.out.println(0b10000000000000000000000000000000); // 32 bits (increment by 1)
/* Both print -2147483648 */
/************************************************************************************/
// And if you keep increasing the binary literal, its actual value
// will be decreased until you reach the maximum binary literal and
// its actual value will be -1.
System.out.println(0b11111111111111111111111111111111); // 32 bits
/* Prints -1 */
Run Code Online (Sandbox Code Playgroud)
如您所见,文字二进制文件的实际值(增量)从最大值跳到int最小值,然后继续减小直到达到-1,这是文字二进制文件的最大值.
这是一个错误吗?或者它与签名/未签名的号码有关?
小智 20
您正在使用有符号整数.位32(左起第一个)是符号位.它是1表示它是负数,0表示正数.然后执行二进制补码以给出-1的值.在这里阅读:
http://tfinley.net/notes/cps104/twoscomp.html