سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top