I have this code:

if((bob.prop & 0x100) == 0x100) { // some code } 

I found that this part:

bob.prop & 0x100 

means

is bob.prop set to 0x100?

So, I think it gives me true or false. But the result of this code is comparing with 0x100 also:

if((bob.prop & 0x100) == 0x100) { 

What is it? What does it mean?

1

2 Answers

0x100 in binary is 0000000100000000, which has its 9th bit set.

Doing bob.prop & 0x100 filters out that 9th bit from bob.prop. For example:

bob.prop & 0x100 1010110101110010 & 0000000100000000 gives 0000000100000000 0110110001101011 & 0000000100000000 gives 0000000000000000 

It does this because it is the bitwise AND of the two operands. That means the result will only have bits set where bits are set in both of the operands.

You are then checking whether the result is equal to 0000000100000000, which is the same as asking "Was the 9th bit set?"

It is not necessary to perform this final comparison, because any integer value greater than 0 will convert to true, while 0 will convert to false. You could just write:

if(bob.prop & 0x100) 
12

the bob.prop & 0x100 is doing a bitwise and of bob.prop with 0x100. The if statement is ensuring that equals 0x100.

So the first test is evaluating an expression, and putting it in the if checks if it matches 0x100.

Note that you are not testing that bob.prop is set to 0x100, rather than are checking whether one bit is set. So the expression would be true for input of 0x100, 0x101, 0x102, 0xfff, ...

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.