Access to nth bit without a conditional statement

牧云@^-^@ 提交于 2019-12-01 23:57:39

问题


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.


回答1:


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



回答2:


I'm fuzzy about the intent of your question—it seem like homework. Depending on what your actual needs are (like is says in the question title or in the text), one of these will work in most any C implementation:

int hasoddbitset (int v)
{
     return (v & 0xaaaaaaaa) != 0;  // for 32 bit ints
}

int isbitset (int val, int bitnum)
{
     return (val & (1 << bitnum)) != 0;
}


来源:https://stackoverflow.com/questions/7211069/access-to-nth-bit-without-a-conditional-statement

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