位元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.