So I'm trying to solve this problem:
You are given random 32bit positive integer, and what you have to do is swap the values of the bits on 3rd, 4th and 5th positions with those on 24th, 25th and 26th position.
Assuming that this is a problem for which you do not want an explicit solution, here is a hint: mask the bits in question using &, do a shift, and then OR then in using bitwise |.
You can "cut out" bits 3, 4, and 5 using the 0x00000034 mask, and bits 24, 25, and 26 using the 0x07000000 mask.
Take a look at this solution to bit reversing problem for an inspiration.
EDIT : (in response to "not a homework" comment) Since this is not a homework, here is a more in-depth explanation:
unsigned int val = ... // your value
unsigned int bits_03_04_05 = val & 0x00000034;
unsigned int bits_24_25_26 = val & 0x07000000;
// Cut out "holes" at bits 3, 4, 5, 24, 25, and 26 of the original value
unsigned int res = val & ~(0x00000034 | 0x07000000);
// Put bits 3, 4, and 5 in place
res |= bits_03_04_05 << 21;
// Put bits 23, 24, and 25 in place
res |= bits_24_25_26 >> 21;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With