Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for bitwise fiddling

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?

like image 539
aherlambang Avatar asked Mar 05 '10 05:03

aherlambang


1 Answers

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"
like image 148
polygenelubricants Avatar answered Nov 20 '22 22:11

polygenelubricants