如何交换前两个连续的不同位元

[英]How to swap first 2 consecutive different bits


What would be a fast and elegant way to swap the first (least significant) 2 different consecutive bits in an unsigned integer?

在无符号整数中交换第一个(最不重要的)两个不同的连续位的快速而优雅的方法是什么?

E.g.

如。

100100 -> 100010
110011 -> 110101

So far I came up with this:

到目前为止,我想到了

unsigned long long special_swap(unsigned long long number)
{
    if (number & 1)
        return (number + 1) ^ ((number ^ (number + 1)) >> 2);
    number = ~number;
    return ~((number + 1) ^ ((number ^ (number + 1)) >> 2));
}

My biggest discontent with the above solution is that it uses the if instruction.

我对上面的解决方案最大的不满是它使用if指令。

2 个解决方案

#1


4  

This is how I would do it:

我是这样做的:

unsigned long long my_swap(unsigned long long number)
{
 unsigned long long x = number ^ (number >> 1);
 return number ^ ((x & -x) * 3);
}

My solution returns 0 when number == 0, whereas the function of the original question returns 1100000000000000000000000000000000000000000000000000000000000000.

当number = 0时,我的解返回0,而原始问题的函数返回1100000000000000000000000000000000000000000000000000000000000000000000000000。

Some explanations: the bits of x contain 0 if the bit at this position is equal to the next bit, and 1 if it is different. (x & -x) is the least significant bit of x, that is to say the first bit difference.

一些解释:如果这个位置的位等于下一个位,那么x的位包含0,如果它不同,则包含1。(x & -x)是x中最不重要的位,也就是第一个位差。

#2


3  

This is the same idea without using an if.

这和不使用if的想法是一样的。

unsigned long long special_swap(unsigned long long number)
{
    unsigned long long t = ((number & 1) << 1) - 1;
    return (number + t) ^ ((number ^ (number + t)) >> 2);
}

The variable t is either 1 or -1, depending on the lsb of the number.

变量t要么是1,要么是-1,这取决于数字的lsb。

Test it live

测试它生活


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/11/04/189abfae318c6b6f6a6c0806da5c888b.html



 
  © 2014-2022 ITdaan.com 联系我们: