Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 542
PICyourBrain Avatar asked Dec 14 '10 12:12

PICyourBrain


People also ask

How do you set certain bits?

Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.

Which macro clears the nth bit in a byte by keeping other bits unchanged?

Clearing bit using macro: We use the bitwise AND operator (&) to clear a bit. x &= ~(1UL << pos); it will clear nth bit. You must invert the bit string with the bitwise NOT operator (~), then AND it.


1 Answers

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.

like image 118
thkala Avatar answered Oct 05 '22 23:10

thkala