JAVA memo2018

2018/09/29 正数变成对应的负数 2の補数(Two's complement)

Math.abs() 絶対値

如何用一个函数就能实现将正数变成对应的负数,将负数变成对应的正数:

 

int turn(int a)  

{  

    a = ~a + 1;                  

    return a;                      

}                                        

  

int main()  

{  

    printf("%d\n", turn(5));  

    printf("%d\n", turn(0));  

    printf("%d\n", turn(-1));  

    return 0;  

} 

 

正数取反加一后,得到就是负数的补码,负数是以补码的形式存在内存中,补码转为原码是就是正数要转化后对应的负数

 

负数取反加一后,得到一个补码,但正数的补码原码一样

 

注意:取反和取反码是不同的两个概念,运算时都是补码形式参与运算,因为有负数参与

10 二进制:  1010 

  1の補数  0101

  2の補数 10110   (1(-) 0101+1)

1     public static void main(String[] args) {
2         int i = -10;
3         int plus = ~i+1;
4         System.out.println("10 binary :"+Integer.toBinaryString(10));
5         System.out.println("-10 の2の補数 binary:"+Integer.toBinaryString(plus));
6         System.out.println("-10 binary :"+Integer.toBinaryString(i));
7     }

console:

10 binary :1010

-10 の2の補数 binary :1010

-10 binary :11111111111111111111111111110110

 

猜你喜欢

转载自www.cnblogs.com/charles999/p/9722122.html