最高有效位还剩多少未设置位? [英] Number of unset bit left of most significant set bit?

查看:107
本文介绍了最高有效位还剩多少未设置位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假定64位整数 0x000000000000FFFF 表示为

00000000 00000000  00000000 00000000
00000000 00000000 >11111111 11111111

我如何找到取消设置最高有效位(标有>的位)左侧的位?

How do I find the amount of unset bits to the left of the most significant set bit (the one marked with >) ?

推荐答案

// clear all bits except the lowest set bit
x &= -x;     

// if x==0, add 0, otherwise add x - 1. 
// This sets all bits below the one set above to 1.
x+= (-(x==0))&(x - 1);

return 64 - count_bits_set(x);

其中 count_bits_set 是最快的计数版本您可以找到的位。请参见 https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 用于各种位计数技术。

Where count_bits_set is the fastest version of counting bits you can find. See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel for various bit counting techniques.

这篇关于最高有效位还剩多少未设置位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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