Bitwise Operation In C - AnyOddBit

I am having a problem with the last issue of my homework. The function should return 1 if any odd bit is set to 1. Here is what I still have:

int anyOddBit(int x) {
    return (x & 0xaaaaaaaa) != 0;
}

This works fine, but I'm not allowed to use a constant that is large (only 0 to 255, 0xFF is allowed). I am also not allowed to use! =

In particular, this is what I am limited to using:

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. Unary integer operations ! ~
  4. Binary integer operations & ^ | + << >>

I cannot figure out how to do this in these constraints, and I would really appreciate it if someone could point me in the right direction. Thanks in advance!

+3
source share
3 answers

You can use:

!!((   ( x        & 0xff)
     | ((x >>  8) & 0xff)
     | ((x >> 16) & 0xff)
     | ((x >> 24) & 0xff)
) & 0xaa)

"" , ORs , , , . , , .

, ANDing, 0xaa , , , - .

, 0 1, !=, !!, . , !(any-non-zero-value) 0 !0 1.


12 ( 13 ), & 0xff >> 24, ( ):

!!((   ( x        & 0xff)
     | ((x >>  8) & 0xff)
     | ((x >> 16) & 0xff)
     | ((x >> 24)       )
) & 0xaa)

. & 0xaa 24 , & 0xff ( ):

!!((x | (x >> 8) | (x >> 16) | (x >> 24)) & 0xaa)

.

+3

ORs ANDs:

((x>>0) | (x>>8) | (x>>16) | (x>>24)) & 0xaa

(x >> 0) - .

+4

0xaaaaaaaa (0xaa << 24) | (0xaa << 16) | (0xaa << 8) | (0xaa), , ?

+1

All Articles