Hello..
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
}
else{
    // 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..
}
else{
    ...
}

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..

Recommended Answers

All 2 Replies

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. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.