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

文章目录

    • 位运算符
    • 地址和指针
    • 位移运算符
    • 数字在 bitset 下的表现
    • bitset 用法
    • uint castTo int 转换

位运算符

/// @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;
}

你可能感兴趣的:(系统原理,C/C++,笔记,c++,算法)