necromancer
necromancer

Reputation: 24651

set bits 1-3 in an int given an int with only bits 1-3 set as desired

unsigned int x = 0xdeadbeef;
unsigned int y = 0x00000006;
unsigned int z = 0xdeadbee7;

How to compute the value in z from the values in x and y?

Bits 1-3 of y are 011 and I want bits 1-3 of the value in x to be replaced with bits 1-3 of y leaving the other bits as they are.

Upvotes: 1

Views: 183

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504122

It sounds like you should:

  • Mask off bits 1-3 so that they can't be set
  • OR the result with bits 1-3 of y

So:

// 0xe == 8 + 4 + 2 (i.e. bits 1-3)
z = (x & ~0xe) | (y & 0xe);

Note that ~ is the bitwise inverse operator, so to clear 3 bits you take the inverse of those bits set, and use the bitwise AND of that inverse with the current value.

You can just use | y instead of | (y & 0xe) if you know that only bits 1-3 will be set in y.

(Note that I've assumed that by "bits 1-3" you mean the bits with value 8, 4 and 2, using the normal bit-counting mechanism of starting from 0. If you meant "the bottom three bits", that would normally be bits 0-2, and you'd use 7 instead of 0xe in the code.)

Upvotes: 6

Related Questions