CPlusPlus - #001 位运算符

位运算符

1 目标

本文的目的是了解c++的位运算符。

2 说明

操作符功能用法
&按位与a & b
|按位或a | b
^按位异或a ^ b
~按位取反(按位非)a ~ b
<<左移a << b
>>右移a >> b
&=按位与赋值a &= b
|=按位或赋值a |= b
^=按位异或赋值a ^= b
<<=左移赋值a <<= b
>>=右移赋值a >>= b

3 代码

3.1 按位与 &

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    int result = a & b; // 0001 in binary
    std::cout << "5 & 3 = " << result << std::endl;
    return 0;
}

3.2 按位或 |

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    int result = a | b; // 0111 in binary
    std::cout << "5 | 3 = " << result << std::endl;
    return 0;
}

3.3 按位异或 ^

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    int result = a ^ b; // 0110 in binary
    std::cout << "5 ^ 3 = " << result << std::endl;
    return 0;
}

3.4 按位取反(按位非) ~

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int result = ~a; // 1010 in binary (two's complement representation)
    std::cout << "~5 = " << result << std::endl;
    return 0;
}

3.5 左移 <<

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int result = a << 1; // 1010 in binary
    std::cout << "5 << 1 = " << result << std::endl;
    return 0;
}

3.6 右移 >>

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int result = a >> 1; // 0010 in binary
    std::cout << "5 >> 1 = " << result << std::endl;
    return 0;
}

3.7 按位与赋值 &=

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    a &= b; // a = a & b, result is 0001
    std::cout << "a &= 3 -> a = " << a << std::endl;
    return 0;
}

3.8 按位或赋值 |=

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    a |= b; // a = a | b, result is 0111
    std::cout << "a |= 3 -> a = " << a << std::endl;
    return 0;
}

3.9 按位异或赋值 ^=

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    int b = 3;  // 0011 in binary
    a ^= b; // a = a ^ b, result is 0110
    std::cout << "a ^= 3 -> a = " << a << std::endl;
    return 0;
}

3.10 左移赋值 <<=

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    a <<= 1; // a = a << 1, result is 1010
    std::cout << "a <<= 1 -> a = " << a << std::endl;
    return 0;
}

3.11 右移赋值 >>=

#include <iostream>

int main() {
    int a = 5;  // 0101 in binary
    a >>= 1; // a = a >> 1, result is 0010
    std::cout << "a >>= 1 -> a = " << a << std::endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

满天飞飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值