本文共 553 字,大约阅读时间需要 1 分钟。
Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer.
Example 18(010010)
1. Take two's complement(i.e. -n) of the given no as all bits are revertedexcept the first '1' from right to left (10111)2 Do an bit-wise & with original no, this will return no with therequired one only (00010)3 Take the log2 of the no, you will get position -1 (1)4 Add 1 (2)
unsigned int getFirstSetBitPos(int n){ return log2(n&-n)+1;//or log2(n & (n^(n-1)))+1}
转载地址:http://uexti.baihongyu.com/