什么是可切换MSB的最佳方式? [英] What's the best way to toggle the MSB?

查看:201
本文介绍了什么是可切换MSB的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想我的切换号码的最显著位。下面是一个例子:

So I want to toggle the most significant bit of my number. Here is an example:

x = 100101 then answer should be 00101

我有一个64位的机器,所以我没想到的答案是 100000 ..的51 0> .. 100101
我想到的一个办法是计算在我的电话号码的位数,然后切换MSB,但不知道如何来算。

I have a 64 bit machine and hence I am not expecting the answer to be 100000..<51 0's>..100101 One way I thought of was to count the number of bits in my number and then toggle the MSB, but not sure on how to count.

推荐答案

作弊是典当它关闭编译器:有大部分的CPU指令做工作,像这样

The cheat is to pawn it off to the compiler: There are instructions in most CPUs for doing work like this.

以下应该做你想要什么。

The following should do what you want.

i ^ (1 << (sizeof i * CHAR_BIT - clz(i) - 1))

这将转化为 CLZ 指令,该指令计数前导零。

This will translate into the CLZ instruction, which counts the leading zeros.

有关GCC,请参阅:的http:// GCC .gnu.org / onlinedocs / GCC-4.1.2 / GCC /其他-Builtins.html

For GCC, see: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Other-Builtins.html

有一件事情要小心的是,这会导致不确定的行为,如果我== 0

One thing to be careful of is that this results in undefined behavior if i == 0.

您应该替换 CLZ()用正确的内在您的编译器,在海湾合作委员会这是 __ builtin_clz ;在Visual Studio C ++这是 _BitScanForward

You should replace clz() with the correct intrinsic for your compiler, In GCC this is __builtin_clz; in Visual Studio C++ this is _BitScanForward.

这篇关于什么是可切换MSB的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆