[英]Swap right-most N bits between two integers
This question was asked during an onsite C++ coding interview. 在现场C ++编码访谈期间询问了这个问题。 I did NOT provide a good answer during that interview.
在那次采访中我没有提供一个好的答案。 So I was hoping to get feedback and suggestions from folks here at stack overflow.
所以我希望在堆栈溢出时得到人们的反馈和建议。 Now that I've had some more time to come up with a solution, I believe that I wrote a decent solution.
现在我已经有更多的时间来提出解决方案了,我相信我写了一个不错的解决方案。 I think this works OK as along as
a
and b
refer to different integers. 我认为这样可行,因为
a
和b
指的是不同的整数。 If a
and b
refer to the same integer, then that integer would be be clobbered to 0. 如果
a
和b
引用相同的整数,那么该整数将被破坏为0。
void SwapRightMostNBits(int& a, int& b, unsigned int n){
if (n>31) { n=31; }
int mask=static_cast<int>(pow(2,n)-1);
a ^= (b & mask);
b ^= (a & mask);
a ^= (b & mask);
}
I think the intended trick here is 我认为这里的目的是
void SwapRightMostNBits(unsigned int& a, unsigned int& b, unsigned int n){
unsigned int mask=(1U<<n) -1;
unsigned int diff = (a^b) & mask;
a ^= diff;
b ^= diff;
}
Note that this uses 3 XOR's, like your solution, but only one masking operation. 请注意,这与您的解决方案一样使用3个XOR,但只使用一个屏蔽操作。 Plus, this is way friendlier on the CPU registers.
另外,这在CPU寄存器上更友好。 There are no false dependency chains.
没有虚假的依赖链。 And finally, it works if
&a==&b
. 最后,如果
&a==&b
,它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.