Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping bits in a positive 32bit integer in C#

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.

like image 912
Leron_says_get_back_Monica Avatar asked Nov 30 '25 16:11

Leron_says_get_back_Monica


1 Answers

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;
like image 187
Sergey Kalinichenko Avatar answered Dec 03 '25 04:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!