如何在Java中交换两位整数?

如何在Java中交换两位整数?,java,bit-manipulation,swap,Java,Bit Manipulation,Swap,Java中是否有一个内置函数可以用来交换两位 例如: __uu1 u0位3与位0交换并成为u0 1 我知道它可以用一个很长的逐位运算过程来完成,但我想避免这样做。我在详细介绍它,但您可以将它连接到一行中 int temp1 = (i & 0x1) << 3; //extract lowest bit #1 and place at pos# 4 int temp2 = (i & 0x8) >> 3; //extract bit #4 and place

Java中是否有一个内置函数可以用来交换两位

例如:

__uu1 u0位3与位0交换并成为u0 1


我知道它可以用一个很长的逐位运算过程来完成,但我想避免这样做。

我在详细介绍它,但您可以将它连接到一行中

 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
inttemp1=(i&0x1)>3//提取位#4并放置在位置#1处
i=(i&temp1)|(i&temp1)//现在位置4准备好了
i=(i&temp2)|(i&temp2)//现在位置1已准备就绪

这里有一种替代方法,称为增量交换

int t = (i ^ (i >> 3)) & 1;
return i ^ t ^ (t << 3);
intt=(i^(i>>3))&1;
返回i^t^(t j
int d=i-j;

inty=(x^(x>>d))&(1您也可以这样尝试

//positions are indexed from 0 and in order ...[4][3][2][1][0]
//so changing 3 and 1 will make             ...[4][1][2][3][0]
public static int swap(int i, int pos1, int pos2) {

    int bit1 = (i >> pos1) & 1;// bit at pos1
    int bit2 = (i >> pos2) & 1;// bit at pos2

    if (bit1 == bit2)
        return i; // no need to swap since we change 1 with 1 or 0 with 0

    // 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 000001010 with ones at specified positions
    int mask = (1 << pos1) | (1 << pos2);

    return i ^ mask;// TADAM!!!
}
//位置从0开始索引,顺序为…[4][3][2][1][0]
//因此,更改3和1将使…[4][1][2][3][0]
公共静态整数交换(整数i、整数pos1、整数pos2){
int bit1=(i>>pos1)&1;//pos1处的位
int bit2=(i>>pos2)&1;//pos2处的位
如果(位1==位2)
返回i;//不需要交换,因为我们将1更改为1或将0更改为0
//因为我们在这里,这意味着我们需要更改1->0和0->1。
//为此,我们可以使用XOR(^)。
//让我们在指定位置创建掩码000001010

int mask=(1)你希望它不会有多长时间?我认为没有专门交换位的内置函数。不存在这样一个函数“按位操作的长过程”这是一个很好的方法,虽然它可能不会那么长。Java integer不是你所说的1字节。你是说
字节吗?
@PM77-1我猜OP简化了它,不需要写30个空格。
//positions are indexed from 0 and in order ...[4][3][2][1][0]
//so changing 3 and 1 will make             ...[4][1][2][3][0]
public static int swap(int i, int pos1, int pos2) {

    int bit1 = (i >> pos1) & 1;// bit at pos1
    int bit2 = (i >> pos2) & 1;// bit at pos2

    if (bit1 == bit2)
        return i; // no need to swap since we change 1 with 1 or 0 with 0

    // 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 000001010 with ones at specified positions
    int mask = (1 << pos1) | (1 << pos2);

    return i ^ mask;// TADAM!!!
}