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

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

    OK, so you've created a bit mask. (01010101)

     if ((value & bit_mask) == bit_mask)
    

    then you know that each bit that was set in bit_mask is also set in value.


    UPDATE: (after reading the question properly)

    You want to check if every second bit is set to 0. (Not set to 1, as my incorrect answer above checks for)

    There are two equally valid approaches: We make the bit mask the opposite (10101010)

    Then use the OR operator:

    if ((value | bit_mask) == bit_mask)
    

    This checks that each bit that was zero in the bit_mask is zero in value.

    The second approach is to make the bit mask the same (01010101) and use the AND operator:

    if ((value & bit_mask) == 0)
    

    This checks that each bit that is one in the bit_mask is zero in value.

提交回复
热议问题