移位直到位串中的第一个'1'

Qua*_*ich 1 bit-manipulation

有没有一种方法可以移位我的位串,直到我将第一个1作为最低有效位为止?例如

0001000100 right shifts twice to 0000010001
0100001010 right shifts once to 0010000101
0010000000 right shifts seven times to 0000000001
Run Code Online (Sandbox Code Playgroud)

我试图通过按位操作来做到这一点。

Gar*_*rey 5

如果n是某种无符号的int:

while ( (n & 0x1) == 0) n >>= 1;
Run Code Online (Sandbox Code Playgroud)

  • 为了安全起见,最好在移位之前检查n == 0。否则无限循环 (3认同)