Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c - Checking bits of ints to see if they share binary with the power of 2 (bitwise only)

I'm trying to recreate this function:

int test(int x) {
   int i;
   for (i = 0; i < 32; i+=2)
   if ((x & (1<<i)) == 0)
      return 0;
   return 1; 
}

But only using these bit-wise operators: !, ~, &, ^, |, +, <<, and >> (Meaning no loops or if statements either)

I am so confused with this question I have been staring at it for like a hour and am still not sure where to start.

I understand that basically it is taking x comparing it with 2^i where i is 0-31 and then returning 0 if x and 2^i do not share any of the same bits and returning 1 otherwise.

But I feel like there is a more simple, non-bit focused explanation that summarizes this better and if someone could even just give me that it would be a huge help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not clear what the question is here but from:

But I feel like there is a more simple, non-bit focused explanation that summarizes this better and if someone could even just give me that it would be a huge help.

It seems you are simply asking for a description of what the code does. That being the case, your stated understanding is entirely incorrect. The behaviour of the code is simply:

  • Return 1 if all even numbered bits are 1, and zero otherwise.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...