Find if every even bit is set to 0 using bitwise operators

前端 未结 5 1193
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 22:40

I have a 32 bit int I can only access it 8 bits at a time. I need to find out if every even bit is set to 0 and return 0 if its true and 1 otherwise.

So far I am goi

5条回答
  •  攒了一身酷
    2021-01-02 23:14

    There is no need to test every individual byte against a mask of 0x55. Just "or" the bytes together and test the result against the mask:

    return ((a | b | c | d) & 0x55 != 0);
    

    Any even bit set to 1 will make the result of the "and" not be 0 anymore, so it will return 1. If all even bits are 0, then 0 is returned.

提交回复
热议问题