Search code examples
cbitwise-operatorstruthtable

Access to nth bit without a conditional statement


So I have a bit sequence:

1010

1 is the MSB.

My function needs to return an integer of 0 if an odd bit is 0 or a 1 if its a 1.

I cannot use any for loops or anything of that nature to see if I need to return a 0 or 1. Does anyone have any suggestions how to go about this.

I was thinking about using a not operation but I can figure out how to exactly use it.

So far I am using a sequence of 1010...10 and then anding it. Doing that to the above would get me 1010. Now I need to find out if I return a 1 or a 0.


Solution

  • Say we're talking about 32bit integers. I assume you want to know if ANY ODD bit is SET (1).

    To do this we create an integer that looks like this:

    10101010101010101010101010101010
    

    Now, if we AND (&) by this, all the even bits get filtered out. Now if the number is not zero one or more odd bits were set. In C:

    #include <stdint.h>
    
    int hasodd(uint32_t x) {
        // 0xAAAAAAAA = 10101010101010101010101010101010
        // double negation to turn x>0 into 1 and leave 0 alone
        return !!(x & 0xAAAAAAAA); 
    }
    

    If you meant that you should return whether the Nth bit is set, this works. It right-shifts a 1 to the correct position to filter out all the irrelevant bits:

    #include <stdint.h>
    
    int nthbitset(uint32_t x, int n) {
        return x & (1 << n);
    }