位元NOT運算 (~)

C++ 中位元補數運算 (NOT) 的符號以 ~ 表示,~ 不像 & 和 |,而是對運算子右邊的單一運算元進行運算,位元補數運算會針對每一個位元進行二進制的補數運算,會將 0 轉換成 1,1 轉換成 0,請參考以下範例:

         0    1      運算元1
         ———-
         1    0      ~ 運算元1

    int a = 103;    // binary:  00000000000000000000000001100111
    int b = ~a;     // binary:  11111111111111111111111110011000 = -104

你可能會驚訝於 103 經過補數運算的結果居然會是個負數 -104,這是因為 int 變數中最高的位元會被當作符號位元,當這個位元為 1 時表示該數為負數,這種編碼方式又被稱作二補數,詳細資料可以參考維基百科的 二補數

有意思的是,任一個整數 x,其 ~x 的結果就等於 -x-1。

這麼看來,帶有正負符號的整數有時會導致非預期的意外。


語法參考主頁面

本頁由熱血青年 LBU 譯自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.