How do you set only certain bits of a byte in C without affecting the rest?

前端 未结 3 1720
遇见更好的自我
遇见更好的自我 2020-11-30 07:04

Say I have a byte like this 1010XXXX where the X values could be anything. I want to set the lower four bits to a specific pattern, say 1100, while leaving the upper four bi

3条回答
  •  心在旅途
    2020-11-30 07:19

    Use bitwise operator or | when you want to change the bit of a byte from 0 to 1.

    Use bitwise operator and & when you want to change the bit of a byte from 1 to 0

    Example

    #include 
    
    int byte;
    int chb;
    
    int main() {
    // Change bit 2 of byte from 0 to 1
    byte = 0b10101010;    
    chb = 0b00000100;       //0 to 1 changer byte
    printf("%d\n",byte);    // display current status of byte
    
    byte = byte | chb;      // perform 0 to 1 single bit changing operation
    printf("%d\n",byte);
    
    // Change bit 2 of byte back from 1 to 0
    chb = 0b11111011;       //1 to 0 changer byte
    
    byte = byte & chb;      // perform 1 to 0 single bit changing operation
    printf("%d\n",byte);
    }
    

    Maybe there are better ways, I dont know. This will help you for now.

提交回复
热议问题