Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if bit is not set

If I use this: if(value & 4) to check if the bit is set, then how do I check if the bit isn't set?

I tried with if(!value & 4) or if(~value & 4) and if(value ^ 4) but none of them works.

like image 273
Protogrammer Avatar asked Dec 01 '14 19:12

Protogrammer


People also ask

What operator checks to see if a bit is on?

Bitwise AND operation is used to check whether a particular bit is on or off.

What is mean by bit is set or not?

Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0's and 1's. So, the digit 1 is known as set bit in the terms of the computer.

Which Bitset method tests whether all bits from Bitset are set or not?

Member functions Tests whether all bits from bitset are set or not.


4 Answers

When you write if(value & 4), C checks the result to be non-zero. Essentially, it means

if((value & 4) != 0) {
    ...
}

Therefore, if you would like to check that the bit is not set, compare the result for equality to zero:

if((value & 4) == 0) {
    ...
}
like image 136
Sergey Kalinichenko Avatar answered Oct 20 '22 01:10

Sergey Kalinichenko


You could do it many ways, but the easiest (easiest as in requires the least amount of thought) would be just negate the entire expression you already have:

if (!(value & 4))
like image 27
Kevin DiTraglia Avatar answered Oct 19 '22 23:10

Kevin DiTraglia


Simply:

if ((value & 4) == 0)

Why?

If value is 01110011

Then

01110011
&
00000100
--------

Will return 0 because 4th bit is off.

like image 43
Maroun Avatar answered Oct 20 '22 00:10

Maroun


the line from hastebin is poorly written, has unreachable code and depends heavily on the Precedence of the C operators. And doesn't work as expected.

The line from hastebin:

if( cur_w > source.xpos + source.width
&&
!(source.attributes & DBOX_HAS_SHADOW) )
{
    break;
    return; 
}

it should be written as:

if( (cur_w > (source.xpos + source.width))  // has curr_w exceeded sum of two other fields?
    &&
    ((source.attributes & DBOX_HAS_SHADOW) != DBOX_HAS_SHADOW ) //is bit == 0?
{
    break;
}
like image 29
user3629249 Avatar answered Oct 19 '22 23:10

user3629249