How can I check my byte flag, verifying that a specific bit is at 1 or 0?

前端 未结 10 1182
花落未央
花落未央 2020-12-08 05:11

I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.

10条回答
  •  我在风中等你
    2020-12-08 05:24

    As an extension of @Daoks answer

    When doing bit-manipulation it really helps to have a very solid knowledge of bitwise operators.

    Also the bitwise "AND" operator in C is &, so what you are wanting to do is:

    unsigned char a = 0xAA; // 10101010 in hex
    unsigned char b = (1 << bitpos); //Where bitpos is the position you want to check
    
    if(a & b) {
        //bit set
    }
    
    else {
        //not set
    }
    

    Above I used the bitwise "AND" (& in C) to check whether a particular bit was set or not. I also used two different ways of formulating binary numbers. I highly recommend you check out the Wikipedia link above.

提交回复
热议问题