Linked Questions
11 questions linked to/from How to replace bits in a bitfield without affecting other bits using C
3173 votes
28 answers
1.7m views
How to set, clear, and toggle a single bit
How can I set, clear, and toggle a bit?
1574 votes
11 answers
944k views
What are bitwise shift (bit-shift) operators and how do they work?
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)... At a core level, what does bit-shifting (<<, >&...
74 votes
9 answers
101k views
Algorithm to generate bit mask
I was facing this unique problem of generating a bit-mask based on the input parameter. For example, if param = 2, then the mask will be 0x3 (11b) if param = 5, then the mask will be 0x1F (1 1111b) ...
27 votes
4 answers
63k views
How do you set only certain bits of a byte in C without affecting the rest?
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 ...
5 votes
7 answers
47k views
Mask and extract bits in C
I've been looking at posts about masks, but I still can't get my head around how to extract certain bits from a number in C. Say if we have an integer number, 0001 1010 0100 1011, its hexadecimal ...
4 votes
3 answers
5k views
How can I clear multiple bits at once in C?
How would I simplify all of this into one line? REG &= ~BITA; REG &= ~BITB; REG &= ~BITC; REG &= ~BITD; REG &= ~BITE;
0 votes
2 answers
8k views
How can I clear a certain number of bits in C?
I know there is another post here that is how to clear a single bit, but how about a whole byte? For example, if I had 00000000 00000000 00101100 11000100 and I wanted to clear the second chunk so it ...
0 votes
2 answers
1k views
SPI and writing data to registers
How can I set multiple bits to 0 in C when working with CR registers with SPI? I know that for setting individual bits I do: SPI1->CR1 |= (1<<2); // To set bit 2 SPI1->CR1 &= ~(1<&...
0 votes
1 answer
2k views
Settings Multiple bits at Once in a Bitset
I am working on a toy file system, I am using a bitset to keep track of used and unused pages. I am using an array of ints (in order to use GCC's built in bit ops.) to represent the bitset. I am not ...
1 vote
1 answer
973 views
How to set masked bits to a specified number?
I haven't been able to find an answer to this on Google, nor do I have any better search ideas. If I have a 2 byte number, a mask, and a third number, how do I replace the masked bits with the third ...
-3 votes
2 answers
106 views
Change part of the bits in a short in C++? [closed]
I have packed data of rgba values in an 16 bit short, so for each channel goes 4bit, how can I change specific channel only, lets say I want to change red channel to it's value devided by two. I know ...