How to find the LEFT MOST set bit in an unsigned integer.
Example:
00*1*0 0001 0100 0010 is a 16-bit unsigned integer. We have to find the
left most set bit position (Starting with 0 from right side )
which is 13th position in our example. How to find this. Can any one pls
give any suggestions.
keep on left shifting the number till it becomes 0. the moment it becomes
0, the count of how many times you had to right shift the number to get 0
is the answer.
On Thu, Jun 14, 2012 at 11:45 AM, Krishna Kishore
kknarenkris...@gmail.comwrote:
How to find the LEFT MOST set bit in an unsigned
sorry note its right shifting in my above post instead of left shift!
On Thu, Jun 14, 2012 at 12:47 PM, Anika Jain anika.jai...@gmail.com wrote:
keep on left shifting the number till it becomes 0. the moment it becomes
0, the count of how many times you had to right shift the number to get 0
unsigned int v; // 32-bit word to find the log base 2 of
unsigned int r = 0; // r will be lg(v)
while (v = 1) // unroll for more speed...
{
r++;
}
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
-
Azhar.
On Thu, Jun 14, 2012 at 12:48 PM, Anika Jain
for 16bit ..take a number n = 1000
let x be the number mentionf in a question
pos = -1
while (1){
if(x n){
pos++
exit}
else
n ยป=1
}
pos is the answer
if pos is greater than numbr of bits then x doesnt hv set bits
How to find the LEFT MOST set bit in an unsigned integer.
Example:
there are two approaches we can take
one is of anika i.e. shifting a no. right till it becomes 0 and count no.
of shifts
int main()
{
int x=10;
int cnt=-1;
while(x)
{
x=1;
cnt++;
}
printf(%d,cnt);
}
another is of aditya in which we didn't change the original no.
instead take a new no. n=pow(2,15)
It is equal to counting leading zeros.
previous codes run in O(32).
this code (
http://codingways.blogspot.com/2012/06/count-leading-zero-bits-in-integer.html
) runs
in O(4)
Regards,
Hassan
On Thu, Jun 14, 2012 at 2:34 PM, utsav sharma utsav.sharm...@gmail.comwrote:
there are two approaches we