Home > front end >  Using Bitwise in C, I have a problem that says return 1 if any bit of x = 0, else return 0
Using Bitwise in C, I have a problem that says return 1 if any bit of x = 0, else return 0

Time:10-05

The questions says:

The expression evaluates to 1 when the following conditions are true and to 0 when they are false. Assume x if of type int.

The expression is: Any bit of x equals 0

One answer I found is

return !!~x;

I don't understand why you need the ~. I know the ~ flips all of the bits. What is the point of flipping all of the bits?

CodePudding user response:

lets see an example, assume size of int is 32-bit

case 1:

x is all ones (no zero bit)

x    =  FFFF FFFF FFFF FFFF (in hex)
~x   =  0000 0000 0000 0000 (in hex)
!~x  =  0000 0000 0000 0001 (in hex) // as !(0) = 1 and !(any other value) = 0
!!~x =  0000 0000 0000 0000 (in hex)

and so !!~x will be evaluated to false as there are no zero bits

case 2:

x contains combinations of 1 and 0 (at least one zero bit)

x    =  F0EF F31F 4F5F A0D1 (in hex)
~x   =  0F10 0CE0 B0A0 5F2E (in hex)
!~x  =  0000 0000 0000 0000 (in hex) // as !(0) = 1 and !(any other value) = 0
!!~x =  0000 0000 0000 0001 (in hex)

and so !!~x will be evaluated to true as there are some zero bits

case 3:

x is off all zero bits (no one bit)

x    =  0000 0000 0000 0000 (in hex)
~x   =  FFFF FFFF FFFF FFFF (in hex)
!~x  =  0000 0000 0000 0000 (in hex) // as !(0) = 1 and !(any other value) = 0
!!~x =  0000 0000 0000 0001 (in hex)

and so !!~x will be evaluated to true as there are some zero bits


also, you can try

return !!(x ^ ~0);

it works the same principle.

CodePudding user response:

When you convert an integer to boolean, a value of zero becomes false and any other value becomes true. So, it can only tell zero from non-zero.

You want your program to do the opposite: return 1 if any bit is zero, and 0 if no bits are zero, i.e. all bits are one. If all bits of x are 1, then ~x will be 0. If you convert that to boolean you get false. Any other x has to have at least one zero, and so at least one bit of ~x is a 1 and converting to boolean yields true. That's what you want.

But now you have to convert ~x to boolean. You can use an if statement, but to get as concise an expression as possible, you can use the negation operator ! to reverse true and false. But that's the opposite of what you want~ Of course, you can just apply another ! operator to reverse it again. i.e. !!~x gets you what you want.

CodePudding user response:

The values of x that satisfy "any bit of x equals 0" are all values except the one where all bits are set.

The only value that evaluates to false is 0, that is the one where none of the bits are set.

If you flip all the bits of x and evaluate it as a boolean, all values that satisfy the expression will evaluate to true. So if ~x != 0, there is a bit of x that is not set and x satisfies the expression.

!!x is just a shorthand for x ? 1 : 0 or x != 0.

  • Related