0

I had to create a function that can be given an int with up to 32 bits. It is supposed to return 1 if an odd bit is 1 and 0 otherwise. I understand that if it does not match the mask it returns zero, but I don't understand why it returns one if it matches the mask. Is it because after the & comparison the result does not equal 0 and therefore returns true which is one?

int any_odd_one(unsigned x)
{

return (x&0xAAAAAAAA)!=0;
Stan
  • 13
  • 2
  • Are you saying it doesn't work, or that you don't understand why it does work? The result of a boolean expression in C is `0` or `1`. The `&` is not "a comparison" it is a bitwise mask. The comparison is in the `!=`. – Weather Vane Mar 27 '16 at 19:08
  • It works, but I wasn't sure why it was returning 1. And thanks for answering my question. – Stan Mar 27 '16 at 19:12

1 Answers1

0

& is the bitwise and operator, it works by taking a bit from the left argument and the same bit from the right argument, doing an 'and' operation on them, and then it saves the result as a bit in the result. It does this for every bit.

Because the result of an 'and' can only be '1' when both arguments are '1', using 0xAAAAAAAA as one argument has the same effect as setting each even bit of the second argument to '0', and leaving all odd bits as they are.

If the result of the above is '0', that means all odd bits were '0'.

Also remember that anything else than '0' is converted to true when an integer is converted to a boolean.

alain
  • 11,939
  • 2
  • 31
  • 51