在二进制数中找到第一个置位 [英] finding the first set bit in a binary number

查看:98
本文介绍了在二进制数中找到第一个置位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从右到左查找二进制数中的第一个置位;我想出了以下解决方案:

I need to find the first set bit in a binary number from right to left; I came up with this solution:

int cnt=0;
while (number& 1 ==0)
{
    cnt++;
    number>>=1;
}

有更好的方法吗?一些巧妙的位操作技术?

Is there a better way of doing it? Some clever bit manipulation technique?

推荐答案

如果您希望它很快,可以使用位扫描指令(bsfbsr)或

If you want it to be fast, bitscan instruction (bsf, bsr) or bit-twiddling hack is the target to go.

使用开关案例表来提高性能的想法不过是不成熟.

The idea of using switch-case table to improve performance is nothing but immature.

这篇关于在二进制数中找到第一个置位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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