JAVA memo2018

2018/09/29 正數變成對應的負數 2の補數(Two's complement)函數

Math.abs() 絶対値spa

如何用一個函數就能實現將正數變成對應的負數,將負數變成對應的正數:code

 

int turn(int a)  blog

{  內存

    a = ~a + 1;                  console

    return a;                      class

}                                        二進制

  

int main()  static

{  di

    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

相關文章
相關標籤/搜索