So, in university they never mentioned the bitwise operators and the work with them. And now I've realised their power in the game development and I want to use them properly, and I'm doing fine, but I can't understand something..

If I'm comparing two integer numbers like this:

int num = 8;
if(num & 8){
    // if number is equal to 8 it will show true
    // if not, it will show false

This seems to work fine, but once I try this:

int num = -8;
if(num & 8){
    // it acts as the previous example..

It executes the true block..
I guess this means that it thinks -8 and 8 are the same, because it's not really recorded as -8? (I'm not so sure if i'm right..)

I know that I need to convert the bits of the integer, and then add a '1' to the last bit to convert a integer to negative.
But how is this going to happen in C or C++?
Is there any function that does this for me?
Sorry for the low English..

3 Years
Discussion Span
Last Post by Nimerion

Bit-wise comparison != numerical comparison. In a your comparison it is only looking to see if the fourth bit is set.. For -8 the top bit is set for the negative, as is the fourth bit, hence your problem. For a bit comparison of two numbers do this:

if ((a&b) == a) // a==b


I see, so it checks only the rightmost bit of the two numbers, wich happens to be, [0]1000 and [1]1000.
Only that the sign bit is being ignored, if it's positive I guess..
Thank you very much, I think I've got it now. :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.