0

If I have a 16-bit number named n and another 16-bit number named n2, and I want to set the first 8 bits of n2 to n. Only the first 8 bits of n should be the same as n2, the remaining 8 should not change. What should I do in such a case? I tried shifting the numbers by 8 but I don't know how to extract the MSB of n and set it to the MSB of n2 and then shift.

Can someone please help me out?

Thanks!

1 Answers1

2

You could zero the first 8 bits of n2 and than or in the first 8 bits of n:

n2 &= 0xFF00;
n2 |= (n & 0x00FF);

Edit for Eric Postpischil comment, the following code will change the most significant byte of n2 to the most significant byte of n.

n2 &= 0x00FF;
n2 |= (n & 0xFF00);
earthling
  • 620
  • 6
  • 20
  • OP’s reference to “MSB” indicates the “first 8 bits” they want to set are the high bits, not the low bits. – Eric Postpischil Apr 16 '21 at 09:16
  • 1
    @EricPostpischil, you are right, I added it to my answer. The question says "the first 8 bits", which in my head are the bits 0..7 and not 8..15, that's where I mixed it up :) – earthling Apr 16 '21 at 09:32