https://en.cppreference.com/w/cpp/language/operator_precedence

    ● 接收右值,进行位运算,返回右值

    ● 除取反外,其它运算符均为左结合

    ● 注意计算过程中可能会涉及到 integral promotion

    1. #include <iostream>
    2. int main()
    3. {
    4. signed char x = 3;
    5. signed char y = 4;
    6. std::cout << (x & y) << std::endl;
    7. }

    Insight:

    1. #include <iostream>
    2. int main()
    3. {
    4. signed char x = 3;
    5. signed char y = 4;
    6. std::cout.operator<<((static_cast<int>(x) & static_cast<int>(y))).operator<<(std::endl);// integral promotion
    7. }

    ● 注意这里没有短路逻辑

    ● 移位操作在一定情况下等价于乘(除) 2 的幂,但速度更快

    ● 注意整数的符号与位操作符的相关影响
    – integral promotion 会根据整数的符号影响其结果

    1. #include <iostream>
    2. int main()
    3. {
    4. signed char x = 0xff;
    5. unsigned char z = 0xff;
    6. auto y1 = ~x;
    7. auto y2 = ~z;
    8. std::cout << y1 << std::endl;
    9. std::cout << y2 << std::endl;
    10. }

    分析:

    1. 变量 x signed char 类型,0xff --> 255 --> 111111111是其符号位,此时进行整型提升,从原来占八位的char类型提升为占32位的int类型,因此在其前面补1,保证其符号,也就是11111111111111111111111111111111,再取反,变成0000000000000000000000000000000,输出结果也就是0
    2. 变量 z unsigned char 类型,0xff --> 255 --> 11111111,此时进行整型提升,从原来占八位的char类型提升为占32位的int类型,因此在其前面补0,也就是00000000000000000000000011111111,再取反,变成11111111111111111111111100000000,输出结果也就是-256

    – 右移保持符号,但左移不能保证