Search code examples
cbit-manipulationbitwise-operatorstruthtable

How to use bitwise operators to return a 0 or 1


My function takes in a 32 bit int and I need to return a 0 or 1 if that number has a 1 in any even position. I cant use any conditional statements I also can only access 8 bits at a time.

Here is an example input: 10001000 01011101 00000000 11001110

1) Shift the bits and and them with AA(10101010) and store each one in a variable.

int a = 10001000
int b = 1000
int c = 0
int d = 10001010

Now I need to return a 0 if there were no odd bits set and 1 if there were. As we can see there were. So I need to combine these into one number and then use the !! operator to return 0 or 1. This is where I am having trouble.

int valueToReturn = a | b | c | d;

Now I need to say:

return !!valueTOReturn; 

It is not return the right value can anyone give me any insight???

I cannot use any condition statements like || &&

I figured it out. Everything I said gives the right answer but I was grabbing the wrong value for one of my variables. Thanks for all the help!


Solution

  • 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);