2015-01-01 62 views
0

为什么这段代码转换为int的Java

public static void main(String[] args){ 
    //       | | | | | | | |  
    int N = (int)Long.parseLong("10110011001100111111001111111100", 2); 
    System.out.println(Integer.toBinaryString(N)); 
    N = Integer.parseInt  ("-0110011001100111111001111111100", 2); 
    System.out.println(Integer.toBinaryString(N)); 
    N = Integer.parseInt  ("+0110011001100111111001111111100", 2); 
    System.out.println(Integer.toBinaryString(N)); 
} 

输出:

10110011001100111111001111111100 
11001100110011000000110000000100 
110011001100111111001111111100 

的Javadoc道: “ - 可以指定标志,以表示负值'”。为什么前两个二进制字符串不同?

+11

嗯,这是两个互补的工作方式 – fge

+0

http://en.wikipedia.org/wiki/Signed_number_representations#Two .27s_complement –

+2

你期望它做什么? –

回答

0

这就是这两个补码如何工作。为了否定一个数字,它将所有的位反相,并将结果加1。

例子: 否定 11110001 ----------> 00001111