是否有一个内置的函数在Java中,我可以用它来交换两个比特?
例如:_ _ _ _ 1 _ _ 0 bit 3与bit 0交换成为_ _ _ _ 0 _ _ 1
我知道这可以用一个很长的按位操作过程来完成,但我想避免这样做。
你也可以这样做
//positions are indexed from 0 and in order ...[4][3][2][1][0]
//so changing 3 and 0 will make ...[4][0][2][1][3]
public static int swapBits(int n, int pos1, int pos2) {
int bit1 = (n >> pos1) & 1;// bit at pos1
int bit2 = (n >> pos2) & 1;// bit at pos2
if (bit1 == bit2) // no need to swap since we change 1 with 1 or 0 with 0
return n; // so we can return original value
// Since we are here it means that we need to change 1->0 and 0->1.
// To do this we can use XOR (^).
// Lets create mask like 000001001 with 1 at positions which need "reversing"
int mask = (1 << pos1) | (1 << pos2);
return n ^ mask;// TA-DAH!!!
}
还有另一种方法,叫做delta-swap。
int t = (i ^ (i >> 3)) & 1;
return i ^ t ^ (t << 3);
或者更一般的:
static int swap(int x, int i, int j)
{
// precondition: i > j
int d = i - j;
int y = (x ^ (x >> d)) & (1 << j);
return x ^ y ^ (y << d);
}
我正在详细制作,但您可以将其合并为一行
int temp1 = (i & 0x1) << 3; //extract lowest bit #1 and place at pos# 4
int temp2 = (i & 0x8) >> 3; //extract bit #4 and place at pos #1
i = (i & temp1) | (i & ~temp1); //now pos #4 is ready
i = (i & temp2) | (i & ~temp2); //now pos #1 is ready