# How to locate the bit in bits string?

tuxagb alessiogiovanni.baroni at gmail.com
Tue Apr 28 17:17:38 CEST 2009

```On 28 Apr, 16:36, Li Wang <li.wan... at gmail.com> wrote:
> Hi:
>
> If I use an integer to represent bits:
> e.g. 99 represents '1100011'
>
> How can I locate, say the second bit of 99(i.e. '1')?
>
> Although bin(99)[4] could be used to locate it, this transform cost
> too much memory (99 only needs 2Bytes, while string '1100011' needs
> 7Bytes).
>
> Anyone knows how to locate  the second bit without using bin() function?
>
> Thank you very much:D
>
> --
> Li
> ------
> Time is all we have
> and you may find one day
> you have less than you think

If we consider 8 bit, a solution may be the follow:

>>> a = 99  # bin(a) = 0b1100011
>>> 0b11111101 & a
97
>>> 0b11101111 & a
99

as you view, you set the nth bit to 0, and view if the result is same
as 'a'. If is same
then the nth bit doesn't set. If you write the above code in a loop,
you can test which bit
you want.

Hi.

```