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

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

    EDIT: I got confused by the original question and followed OP in the negation thing - so basically this solves the reverse problem. Andrew Sheperd's edited solution starts back from the original problem and solves it in 1 step. Rudy Velthuis also offers an interesting approach.

    If your bytevalue AND 01010101 == 01010101 all bits selected by the mask are 1 in the original byte value.

    In sortof pseudo C:

    unsigned char mask = 0x55;
    
    if ((byteval & mask) == mask) {
        printf ("all set");
    }
    

    or a slightly fancier xor based variation

    unsigned char mask = 0x55;
    
    if (!((byteval & mask) ^ mask)) {
        printf ("all set");
    }
    

    Btw, the if is very easy to get rid of for the final result ...

提交回复
热议问题