2

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!

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • You seem to be mixing binary and decimal representations in strange ways in your code. I'm not sure exactly what you're trying to accomplish but you can use `std::bitset` to print the binary representation of a number as in this question: http://stackoverflow.com/questions/7349689/c-how-to-print-using-cout-the-way-a-number-is-stored-in-memory – mattnewport Aug 25 '15 at 20:56
  • This is essentially the same question as you asked about go: http://stackoverflow.com/q/32213029 – harold Aug 25 '15 at 20:59
  • 2
    your `tob` accepts `int` and returns `int`, and you print it with %d, and you ask us how come unsinged numbers becomes negative? – user3528438 Aug 25 '15 at 21:16

2 Answers2

6

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
2

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

Use a std::bitset for four bits.

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

Example on Coliru

Émilien Tlapale
  • 903
  • 5
  • 11