开发者

I am not getting the answer I expect using the Bitwise NOT operator. Would appreciate some help

I am working though a C++ book trying to learn some things. I am stuck on one thing, the bitwise not. I understand it flips all the bits but it is not working how I expect in C++. Here is the relevent code.

letter = 'A';  // dec = 65   hex = 0x41   binary = 0100 0001
cout << endl << "Bitwise NOT" << endl;
cout << "Letter: " << letter << " = " << insertSpaces(toBinary(letter)) << endl;
int notletter = ~letter;
cout << "~Letter: " << notletter << endl;


string insertSpaces(string binary)
// insert spaces into a binary number string for readability
{
    int pos = 4;
    int len = binary.length();

    while (pos < len)
    {
        binary.insert(pos, " ");
        pos = pos + 5;   // 5 because it includes space
        len++;           // space makes length longer
    }
    return binary;
}

string toBinary(int letter)
{
    string result = "";
    while (letter > 0)
    {
        result = t开发者_如何学PythonoString(letter % 2) + result;
        letter /= 2;
    }
    int rem = result.length() % 4;
    if (rem > 0)
    {
        int zeros = 4 - rem;
        for (int i = 0; i < zeros; i++)
            result = "0" + result;
    }
    return result;
}

Here is the output.

Bitwise NOT
Letter: A = 0100 0001
~Letter: -66

The answer should be 190 or 1011 1110 in binary so why did I get -66? I am using Visual C++ 2010.


Use an unsigned integer rather than a signed one. The reason you got a negative number is because most computers today use two's complement.

This is what your data looks like before and after the bitwise not:

before     | after
0100 0001  | 1011 1110

(actually there's probably 32 bits there since you're using an int and not a char; the best type to use here would probably be uint8_t)

In two's complement, a number is negative if the most significant bit is 1. After the not, it is. In two's compliment, to negate a number, you take the bitwise not and add 1. If you take 1011 1110 and invert it, you get 0100 0001. Now you add one, resulting in 0100 0010. If you convert that to decimal, you get 66. Add the minus since the first bit was one, and you get -66, the unexpected value.


You are dealing with a signed number in Two's Complement. The value has exceeded the largest positive value (127) and wrapped to the negative space.

You can print it as an unsigned character/integer (i.e., (unsigned int)notletter or static_cast<unsigned int>(notletter)).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜