How to use bitwise operators to return a 0 or 1

☆樱花仙子☆ 提交于 2019-12-04 21:08:18

First of all, you're not storing bits the way you're thinking.

int a = 10001000

is actually 10,001,000 (which in binary, b100110001001101001101000).

You say that the function takes in a 32-bit integer, so what you can do is extract each of the 8-bit portions like so:

unsigned char a, b, c, d;
a = (unsigned char)(input & 0xff);
b = (unsigned char)((input >> 8) & 0xff);
c = (unsigned char)((input >> 16) & 0xff);
d = (unsigned char)((input >> 24) & 0xff);

Now you can perform your masking/testing operation:

return (0xAA & a) | (0xAA & b) | (0xAA & c) | (0xAA & d);

But, I don't know if I am understand correctly, if a have a 32 bit number, can have ALL bit OFF ONLY if is 0.

if(input_number == 0 )
return 0;
else 
return 1;

As bdares says, it is just a lot of bitwise operations... evenbit_int evaluates to requested value.

#define evenbit_byte(x) (((x) >> 1 | (x) >> 3 | (x) >> 5 | (x) >> 7) & 1)
#define evenbit_int(x) (evenbit_byte(x) | evenbit_byte(x >> 8) | evenbit_byte(x >> 16) | evenbit_byte(x >> 24))

or slightly more optimized

byte evenbits(DWORD x)
{ 
  byte a = x >> 8;    
  byte b = x >> 16;    
  byte c = x >> 24;
  return (evenbit_byte(x) | evenbit_byte(a) | evenbit_byte(b) | evenbit_byte(c))
}

If you can't use conditionals, you'll have to do this the ugly way: take the bit of each even-index bit and return the OR of them. You can skip the mask. This is kind of stupid though, and reeks of badly made homework.

Edited my answer to remove the erroneous first part.

It appears that arnaud576875 is correct about the logical ! operator: http://www.gnu.org/s/gnu-c-manual/gnu-c-manual.html#The-Logical-Negation-Operator

Until someone can find a C99 specification reference (GNU implementation might deviate from it), I guess I won't know for sure, but I suspect your version of C is as I described earlier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!