Continue to Site

# How to find the least most significant bit set in a byte

Status
Not open for further replies.

#### gprashanth911

##### Newbie level 5
Hi,

I am looking for all the possible solutions to find the least most significant bit set in a byte. Provided the algorithm should be O(1). If any one has any sort of info please share.

Hi, pls explain wot do you mean by "least most significant bit set", and I will be able to help.
Kr,
Avi
http://www.vlsiip.com

A function like this should work. It's to find the LSB of a byte. It returns aa value 0 to 7 or -1 for no bit set You could do a zero test rigth off the bat if you wanted (if value == 0 return -1). I haven't tested it so be warned.

signed int Find_Byte_LSB(value)
{

int i = 0;

while (i <= 7)
{
if (1 << i && value)
return i;
i++;
}

return -1;

}

First of all there is no such a thing as "the least most significant bit". There is either least or most significant bit (LSB or MSB). Where are they located in the byte is actually depends on "bit endianness" (https://en.wikipedia.org/wiki/Endianness)
Although usually MSB is the left most bit in the byte and LSB - right. Thus to find what "ByteVar" has in MSB or LSB, this code could be used (or some derivative of that):

for MSB
bit = (ByteVar & 0x80) ? 1: 0;
or
bit = (unsigned byte)(ByteVar & 0x80) >> 7;

for LSB
bit = (ByteVar & 0x01) ? 1: 0;
or simple
bit = ByteVar & 0x01;

Cheers.

AND the value with 0x01 if the result is 1 last bit is set else not set.

Just 3 step away

Let say no = x

1: substract the number by 1 => x-1
2: invert the result => ~(x-1)
3: And the result with the orginal number => X && [~(x-1)]

Then right shift he result untill u get the set bit ....deal done...

Status
Not open for further replies.