立即获取整数中最左边有效位的索引

NL6*_*628 0 c++ bit-manipulation built-in bit findfirst

如何从左到右而不是从右到左扫描整数(二进制)?我知道我可以从左边开始尝试每一位,然后记录最左边的位,但是有没有更快的方法?是否有一个内置函数可以立即找到整数中最左边的有效位(即 1)?

我知道从右到左,我可以做类似的事情

int myInt = 1234;
for(int i = 0; i < 32; i++) {
  int curr_bit = myInt & (1 << i);
  // do something with curr_bit
}
Run Code Online (Sandbox Code Playgroud)

但是,我想从最左边的可用位开始,并且我想要它的数字“x”,以便它1 << x指向该确切的数字(正如旁注,我正在尝试实现重复平方,并且我需要在我的代码)。

任何帮助将不胜感激!

phu*_*clv 5

This is called Find first set and most modern architectures have an instruction to do that quickly. In C++20 it can be done with std::countl_zero in the <bit> header

int left_most_bit_pos = sizeof(myInt)*CHAR_BIT - std::countl_zero(myInt);
int left_most_bit = myInt & (1 << left_most_bit_pos)
Run Code Online (Sandbox Code Playgroud)