负数的计算机表示:
整数-3在计算机中的二进制表示为:
- 先取 |-3| (绝对值)的原码:00000000 00000000 00000000 00000011
- 得反码: 11111111 11111111 11111111 11111100
- 得补码(反码+1): 11111111 11111111 11111111 11111101
按位操作
所有的位运算都是针对每个比特位进行计算的
-
按位与运算符(&):
例如:3&5 即 0000 0011 & 0000 0101 = 0000 0001 因此,3&5的值得1。 -
按位或运算符(|):
例如:3|5 即 0000 0011 | 0000 0101 = 0000 0111 因此,3|5的值得7。 -
按位异或运算符(^):参加运算的两个数据,按二进制位进行“异或”运算。
运算规则:0^0=0; 0^1=1; 1^0=1; 1^1=0;
即:参加运算的两个对象,如果两个相应位为“异”(值不同),则该位结果为1,否则为0。
例如3 ^ 5 即0011 ^ 0101 = 0110 为6 -
取反运算符(~):
- 所有正整数的按位取反是其本身+1的负数,如~(3) = -4
- 所有负整数的按位取反是其本身+1的绝对值,如~(-3) = 2
- 零的按位取反是 -1
-
左移运算符(<<)
左移:丢弃最高位,低位补0// 无符号数 unsigned char short3 = 255 << 1; // 左移溢出 bitset<8> bitset3{ short3 }; // short3 is 254, bitset: 11111110 cout << "short3 is " << static_cast<int>(short3) << ", bitset: " << bitset3 << endl; // 有符号数 signed char short4 = 127 << 1; // 左移溢出 // 二进制: 01111111 左移之后为:11111110 // short4 is -2, bitset: 11111110 cout << "short4 is " << static_cast<int>(short4) << ", bitset: " << bitset<8>(short4) << endl;
-
右移运算符(>>)
右移:丢弃最低位,无符号数高位补0,对于有符号数,正数高位补0,负数高位补1// 无符号数 unsigned char short5 = 255 >> 1; // short5 is 127, bitset: 01111111 cout << "short5 is " << static_cast<int>(short5) << ", bitset: " << bitset<8>(short5) << endl; // 有符号数 char short6 = -1 >> 1; // short6 is -1, bitset: 11111111 cout << "short6 is " << static_cast<int>(short6) << ", bitset: " << bitset<8>(short6) << endl;
eg:
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
cout << (3 & 5) << endl; // 1
cout << (3 | 5) << endl; // 7
cout << (3 ^ 5) << endl; // 6
cout << bitset<32>(-3) << endl;
cout << ~(-3) << endl; // 2
// 无符号左移n位 等同于val = val * (2^n)
unsigned short short1 = 4;
bitset<16> bitset1{ short1 }; // the bitset representation of 4
cout << bitset1 << endl; // 00000000'00000100
unsigned short short2 = short1 << 1; // 4 left-shifted by 1 = 8
bitset<16> bitset2{ short2 };
cout << bitset2 << endl; // 00000000'00001000
// 无符号数
unsigned char short3 = 255 << 1; // 左移溢出
bitset<8> bitset3{ short3 };
// short3 is 254, bitset: 11111110
cout << "short3 is " << static_cast<int>(short3) << ", bitset: " << bitset3 << endl;
// 有符号数
signed char short4 = 127 << 1; // 左移溢出
// 二进制: 01111111 左移之后为:11111110
// short4 is -2, bitset: 11111110
cout << "short4 is " << static_cast<int>(short4) << ", bitset: " << bitset<8>(short4) << endl;
// 无符号数
unsigned char short5 = 255 >> 1;
// short5 is 127, bitset: 01111111
cout << "short5 is " << static_cast<int>(short5) << ", bitset: " << bitset<8>(short5) << endl;
// 有符号数
char short6 = -1 >> 1;
// short6 is -1, bitset: 11111111
cout << "short6 is " << static_cast<int>(short6) << ", bitset: " << bitset<8>(short6) << endl;
return 0;
}
逻辑操作
- 逻辑与:&& and
- 逻辑或:|| or
- 逻辑非:! not