Search code examples
c++bit-manipulationlong-integerbitwise-operatorsbitset

C++ bitwise complement in unsigned integer returns negative values


I am just trying to do the bitwise complement in C++ with ~ operator:

For example:

NOT 0101
--------
    1010

So in the following code, I was expecting to get 1010 but I am getting negative numbers. How is it possible although I define the values with unsigned types?

#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
}

And how do I get 1010 from not 0101 in C++?

Thanks!


Solution

  • unsigned int has normally 32 bits and all of them are being inverted here:

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

    If you want only last 4 bits and zero out the rest, apply a mask:

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

    You can get desired result with simple bitwise XOR too:

    unsigned int z = x ^ 0xf;
    

    By the way, your code will fail to print binary representations of larger numbers because int won't be capable of holding values above 2^32 (starting with 100 0000 0000 (decimal)). For that, I recommend printing with std::bitset or the direct approach in the answer below instead of using tob function.