Swapping bits in a positive 32bit integer in C#

江枫思渺然 提交于 2019-12-02 05:47:19

问题


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.


回答1:


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;



回答2:


How about:

    // snag the values from 3,4,5 (small) and 24,25,26 (large)
    int small = value & (7 << 2), large = value & (7 << 23);

    // remove the old values, and add in the new ones
    value = (value ^ (small | large)) | (large >> 21) | (small << 21);

(which counts bit 1 as the LSB; if you mean bit 0 is the LSB, then adjust the numbers by 1)




回答3:


To solve the problem you use the properties of the bitwise operator& and operator| by applying them between the initial integer value and a mask.

Assuming you have an initial value:

 unsigned int val;// your value

you need to form a mask:

int setLSB = 1;   // 00000001

int atPosition = 4;

// shift the set bit 4 positions to the left
int mask = setLSB << atPosition;   // 00010000

and then use it to retrieve, clear and set bit value:

// get bit at position 4
unsigned int valueOfFourthBit = val & mask;

// clear bit at position 4 and assign to result
unsigned int res = val & ~(mask);

// put the value of the 4th bit at wanted position
int wantedPosition = 21;
res |= valueOfFourthBit << wantedPosition;

If you need a range of consecutive bits, as in your case 3, you can do:

int numberOfSetBits = 3;
int setLSBs = 0

for (int i =0; i < numberOfSetBits; ++i)
{
    setLSBs += (int) Math.Pow(2, i);
}

setLSBs = 7; // 00000111

// and then the masks for getting 3,4,5 and 24,25,26 bits become
int smallPosition = 3;
int largePosition = 24;

int smallMask = setLSBs << smallPosition; // 0x00000034
int largeMask = setLSBs << largePosition; // 0x07000000;

The rest is covered in the existent answers.



来源:https://stackoverflow.com/questions/12413356/swapping-bits-in-a-positive-32bit-integer-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!