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!
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.
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.
First of all, you're not storing bits the way you're thinking.
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:
Now you can perform your masking/testing operation:
As bdares says, it is just a lot of bitwise operations...
evenbit_int
evaluates to requested value.or slightly more optimized