Search code examples
cbit-manipulationbitwise-operators

What is the simplest way to overwrite the bits 10, 11, 12 of an unsigned int to X?


Let val and x be 32-bit unsigned integers. Let x be in the range 0 til 8 (thus, holding at most 3 bits). What is the simplest way to overwrite the bits 10, 11 and 12 of val to match the bits of x? I.e., in such a way that (val >> 10) & 1 == x & 1, (val >> 11) & 1 == (x >> 1) & 1 and (val >> 12) & 1 == (x >> 2) & 1? As an example, this expression accomplishes this:

(val & ~(0x7 << 10)) | (x << 10)

Is it possible to accomplish the same with fewer operations?


Solution

  • The expression you have is the simplest way (though I don't have a proof), assuming both val and x are variables rather than constants. Any decent compiler will compute the constant value of ~(0x7 << 10) at compile time, of course.

    You might want to avoid the duplication by writing an (inline) function or macro if you need this a lot.