Anthony
Anthony

Reputation: 37065

Setting/Casting specific bits or bytes in a set

I have a 16-bit number, like 0x789A and I want to change the 2 most significant bits to 10 (setting the highest and clearing the second-highest) to end up with 0x989A.

I know that I can set the first bit using n | 0x8000 and I can unset the second bit (in php) using n & ~0x4000 but is there a way to "cast" the two bits to 10 in one operation without affecting the lesser bits?

Similarly, I have another 16-bit number, like 0xABCD that I want to change the byte value of the first byte to a different hex value, for instance 5 so that I end up with 0x5BCD. Is there a way to set bytes using bitwise operations? I'm not even sure how to begin for this.

Upvotes: 0

Views: 436

Answers (2)

Barmar
Barmar

Reputation: 781503

This will set the 2 most significant bits to binary 10:

0x8000 | ($n & 0x3fff)

This will set the most signigicant byte to hex 5:

0x5000 | ($n & 0x0fff)

The general idea is that you use 0 bits in the mask to specify the bits you want to replace, 1 to specify the bits to keep, and then OR in the replacement.

Upvotes: 1

Marc B
Marc B

Reputation: 360742

Do it exactly as you had, just do it two bits at a time, e.g

(0x789A & ~0xC000) | 0xC000

    0111100010011010   0x789A
  & 0011111111111111  ~0xC000   ---clear the two relevant bits
  ------------------
 =  0011100010011010   0x389A
  | 1000000000000000   0xC000   --- set their new values
  ------------------
 =  1111100010011010   0xF89A

Upvotes: 1

Related Questions