views:

95

answers:

4

If I have a 32-bit binary number and I want to replace the lower 16-bit of the binary number with a 16-bit number that I have and keep the upper 16-bit of that number to produce a new binary number.. how can I do this using simple bitwise operator?

For example the 32-bit binary number is:

1010 0000 1011 1111 0100 1000 1010 1001

and the lower 16-bit I have is:

                    0000 0000 0000 0001

so the result is:

1010 0000 1011 1111 0000 0000 0000 0001

how can I do this?

+7  A: 

You do this in two steps:

  • Mask out the bits that you want to replace (AND it with 0s)
  • Fill in the replacements (OR it with the new bits)

So in your case,

i32 number;
i32 mask_lower_16 = FFFF0000;
i16 newValue;

number = (number AND mask_lower_16) OR newValue;

In actual programming language implementation, you may also need to address the issue of sign extension on the 16-bit value. In Java, for example, you have to mask the upper 16 bits of the short like this:

    short v = (short) 0xF00D;
    int number = 0x12345678;
    number = (number & 0xFFFF0000) | (v & 0x0000FFFF);
    System.out.println(Integer.toHexString(number)); // "1234f00d"
polygenelubricants
+1. nicely explained.
Mitch Wheat
Mitch Wheat
Done. Also addressed sign extension issue.
polygenelubricants
+2  A: 
(original32BitNumber & 0xFFFF0000) | 16bitNumber
Mitch Wheat
second operation should be OR
Aviator
Thanks! I must have done this millions of times and still managed to type the wrong thing!
Mitch Wheat
+1 This is it!!
TheMachineCharmer
Depending on language, sign extension on the 16bitNumber is an issue.
polygenelubricants
Paul R
+1  A: 

Well, I could tell you the answer. But perhaps this is homework. So I won't.

Consider that you have a few options:

| // bitwise OR
^ // bitwise XOR
& // bitwise AND

Maybe draw up a little table and decide which one will give you the right result (when you operate on the right section of your larger binary number).

Noon Silk
A: 

use & to mask off the low bits and then | to merge the 16 bit value with the 32 bit value

 uint  a = 0xa0bf68a9
 short b = 1

 uint  result = (a & 0xFFFF0000) | b;
John Knoeller