CMU15-213 课程笔记 02/03-Bites、Bytes、Integer

位运算符

/// @brief 复习位运算符
void module1()
{
    int a = 67;
    int b = 109;
    cout << bitset<16>(a) << endl;
    cout << bitset<16>(b) << endl;

    cout << bitset<16>(a & b) << " &" << endl;
    cout << bitset<16>(a | b) << " |" << endl;
    cout << bitset<16>(a ^ b) << " ^" << endl;
    cout << bitset<16>(!a) << " !a" << endl;
}

地址和指针

/// @brief 复习地址和指针
void module2()
{
    int a = 10;
    int *p = &a;
    cout << p << " p's value, a's address" << endl;
    cout << &p << " p's address" << endl;
    cout << *p << " p's point to value";
}

位移运算符

/// @brief shifting 位移
void module3()
{
    int a = 10;
    cout << bitset<16>(a) << endl;

    // 右移, 若不触碰边界即为*2
    a = a << 1;
    cout << bitset<16>(a) << endl;

    // 左移, 若不触碰边界即为/2
    a = a >> 1;
    cout << bitset<16>(a) << endl;
}

数字在 bitset 下的表现

/// @brief unsigned 和 signed
void module4()
{
    short x = 15213;
    short y = -15213;
    short a = 0;
    short b = -1;
    cout << bitset<16>(x) << endl;
    cout << bitset<16>(y) << endl;
    cout << bitset<16>(a) << endl;
    cout << bitset<16>(b) << endl;
}

bitset 用法

/// @brief bitset 使用
void module5()
{
    unsigned short a = 16;
    auto a_set = bitset<5>(a);
    cout << a_set[4] << endl;
    cout << a_set << endl;
}

uint castTo int 转换

/// @brief uint castTo int
void module6()
{
    // 初始化 unsigned a 11111 -> 31
    const char set[6] = "11111";
    auto a_set = bitset<5>(set);
    auto a = a_set.to_ulong();

    // 初始化 signed a 11111 -> -1
    char casted_set[6];
    for (int i = 0; i < 5; i++)
    {
        casted_set[i] = '1' - set[i];
    }
    auto unsigned_set = bitset<5>(casted_set);
    auto unsigned_a = (int)unsigned_set.to_ulong() - 1;

    // logger
    cout << "signed a: " << a << endl;
    cout << "unsigned a: " << unsigned_a << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值