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

血红的双手。 提交于 2019-11-27 13:44:22

问题


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 bits unaffected. How would I do this the fastest in C?


回答1:


You can set all those bits to 0 by bitwise-anding with the 4 bits set to 0 and all other set to 1 (This is the complement of the 4 bits set to 1). You can then bitwise-or in the bits as you would normally.

ie

 val &= ~0xf; // Clear lower 4 bits. Note: ~0xf == 0xfffffff0
 val |= lower4Bits & 0xf; // Worth anding with the 4 bits set to 1 to make sure no
                          // other bits are set.



回答2:


In general:

value = (value & ~mask) | (newvalue & mask);

mask is a value with all bits to be changed (and only them) set to 1 - it would be 0xf in your case. newvalue is a value that contains the new state of those bits - all other bits are essentially ignored.

This will work for all types for which bitwise operators are supported.




回答3:


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 <stdio.h>

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.



来源:https://stackoverflow.com/questions/4439078/how-do-you-set-only-certain-bits-of-a-byte-in-c-without-affecting-the-rest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!