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

前端 未结 5 1191
爱一瞬间的悲伤
爱一瞬间的悲伤 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:06

    Just take some integer variable and store the value in it.

    i= ( a & 0x55 ) + (b & 0x55 ) + ( c & 0x55 ) + (d & 0x55 )
    

    If all the even bits are set to zero,The variable i has 0 value in it else greater than 0.and anything which is not equal to zero it is true in c.

    say

     a = 10101010 & 0x55 ( 01010101) which returns zero,masking all odd bits to zero
    

    similarly

     b & 0x55 and c & 0x55 and d & 0x55 
    

    and if all they result to zero then variable i has zero value in it,else some other value that may be considered as True in c.

提交回复
热议问题