无符号整数 returns 负值中的 C++ 按位补码

C++ bitwise complement in unsigned integer returns negative values

我只是想在 C++ 中使用 ~ 运算符进行按位补码:

例如:

NOT 0101
--------
    1010

所以在下面的代码中,我期望得到 1010 但我得到的是负数。尽管我用 unsigned 类型定义值,但怎么可能?

#include <iostream>
#include <stdio.h>
#include <string>
#include <bitset>
using namespace std;

int tob(int num) {
    if (num == 0)
        return 0;
    return (num % 2) + 10*tob(num/2);
}

long unsigned int tol(string st) {
    long unsigned int num = bitset<100>(st).to_ulong();
    return num;
}


int main()
{
    unsigned int x = tol("0101");
    unsigned int z = ~x;
    printf("%10d (decimal %u)\n", tob(z), z);
    // -110 (decimal -6)
    cout << tob(z) << endl; // -110
    cout << z << endl; // -110
}

我如何在 C++ 中从 not 0101 得到 1010

谢谢!

[…] how do I get 1010 from not 0101 in C++?

4 位使用 std::bitset

std::bitset<4> x("0101");
auto z = ~x;
std::cout << '~' << x << '=' << z << std::endl;

Example on Coliru

unsigned int 通常有 32 位,这里所有的都被反转:

NOT 0000 0000 0000 0000 0000 0000 0000 0101
-------------------------------------------
    1111 1111 1111 1111 1111 1111 1111 1010

如果您只需要最后 4 位并将其余位清零,请应用掩码:

unsigned int z = ~x & 0xf; // 1111 in binary

您也可以通过简单的按位异或得到想要的结果:

unsigned int z = x ^ 0xf;

顺便说一句,您的代码将无法打印较大数字的二进制表示,因为 int 无法保存 2^32 以上的值(从 100 0000 0000(十进制)开始) .为此,我建议使用 std::bitset 或下面答案中的直接方法打印,而不是使用 tob 函数。