Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91510
| Date | 2015-05-30 00:18 +0100 |
|---|---|
| From | John Pote <johnhpote@o2.co.uk> |
| Subject | Re: How to do integers to binary lists and back |
| References | (12 earlier) <8A3659BC-9100-4A3A-9117-47227B3D290B@gmail.com> <CALwzidmgj1y==3iv8Zub+aHyFR3P3okeLBRKu+R92914mDXfqQ@mail.gmail.com> <5522439B-AEFA-400D-9B6F-00613528381F@gmail.com> <555E5A44.20006@o2.co.uk> <555E5CD8.4090704@mrabarnett.plus.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.212.1432941587.5151.python-list@python.org> (permalink) |
On 21/05/2015 23:31, MRAB wrote:
> On 2015-05-21 23:20, John Pote wrote:
>> Hi everyone.
>> I recently had the problem of converting from an integer to its
>> representation as a list of binary bits, each bit being an integer 1 or
>> 0, and vice versa. E.G.
>> 0x53
>> becomes
>> [ 0, 1, 0, 1, 0, 0, 1, 1 ]
>>
>> This I wanted to do for integers of many tens, if not hundreds, of bits.
>> Python very nicely expands integers to any size required, great feature.
>>
>> Just wondered if there was a neat way of doing this without resorting to
>> a bit bashing loop.
>>
>> Looking forward to some interesting answers,
>> John
>>
>>
> I don't know how efficient you want it to be, but:
>
> >>> number = 0x53
> >>> bin(number)
> '0b1010011'
> >>> bin(number)[2 : ]
> '1010011'
> >>> list(map(int, bin(number)[2 : ]))
> [1, 0, 1, 0, 0, 1, 1]
>
Thanks for the replies. Interesting that the offered solutions involve
converting to a binary text string and then the individual chars back to
ints. I had thought this would be a route to solve this problem but it
seemed a bit 'heavy' hence I thought it worthwhile asking the question.
My solution to converting a list of 1s and 0s back to an int is
listLen = len( binList )
n = sum( [ binList[i]*( 2**(listLen-1 - i) ) for i in
range(listLen)] )
In response to Ben Finney's question, I haven't done homework for 40
years! Genuine problem, I had decided that the clearest way to write the
algorithm I was working on was to use lists of 1s and 0s rather than
normal ints.
Thanks for the help,
John
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: How to do integers to binary lists and back John Pote <johnhpote@o2.co.uk> - 2015-05-30 00:18 +0100
csiph-web