bit-manipulationbitmask

Change the bit position in a bitmask


I need to change the order between bit in position 1 and position 2 (starting to count from right to left). How can I do this?

Input Output
1010 1100
1110 1110
0101 0011

I'm trying something such as:

1010 & 0010 to get only the bit in position 1

1010 & 0100 to get only the bit in position 2

my_result = (1010 & 0010) << 1

And after that I need to apply an AND operation with the last 2 digits

partial_result = my_result & 0010

And after that apply some operation to order the position 2 but it seems complicated.


Solution

  • after you use the and to get the bits in position 1 and 2, you can left shift one and right shift the other and and it back.

    input = 1010
    bitpos1 = input & 0010
    bitpos1 = bitpos1 << 1
    bitpos2 = input & 0100
    bitpos2 = bitpos2 >> 1
    
    output = input & 1001  // filter out bits 1 and 2
    output = output | bitpos1 | bitpos2