[Tutor] Extracting bits from an array

Colin Ross colin.ross.dal at gmail.com
Fri Apr 29 13:42:56 EDT 2016


Thank you Michael, this is exactly what I was looking for! Clears things up
on multiple fronts : )

On Fri, Apr 29, 2016 at 2:29 PM, Michael Selik <michael.selik at gmail.com>
wrote:

>
>
> > On Apr 29, 2016, at 1:15 PM, Colin Ross <colin.ross.dal at gmail.com>
> wrote:
> >
> > Hello,
> >
> > I have an array that takes on the following form:
> >
> > x = [1000,1001,1011,1111]
> >
> > The array elements are meant to be binary representation of integers.
> >
> > Goal: Access array elements and extract the first two bits.
> >
> > e.g. Final result would look something like this:
> >
> > x_new = [10,10,10,11]
> >
> > What I have tried:
> >
> > data_indices = range(4)      #  Set up array of values to loop over
> >
> > for idx in data_indices:
> >     f = x[idx]                          # Index into array of x values
>
> Instead of looping over a range of indices, you should loop over the data
> itself.
>
>     for number in x:
>         s = bin(number)
>         print s
>
> >     f_idx = f[:2]                      # Extract first two elements
>
> You couldn't slice an integer. First convert to the binary representation
> in string form. You can strip off the prefix if you just want the digits.
>
>     s = bin(number).lstrip('0b')
>
> Then you can slice off the first two digits if you want. Remember, it's a
> str of digits, not a number.
>
> >     print f_idx
> >
> > I then receive the following error:
> >
> > IndexError: invalid index to scalar variable.
> >
> > Any help with accomplishing my outline dgoal would be greatly
> appreciated.
> >
> > Thank you.
> >
> > Colin
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list