binary number format ? format character %b or similar.

K

Ken Starks

I'm was wanting to format a positive integer in binary,
and not finding it--to my surprise--I rolled my own version.

Is this already in python, or have I missed it somewhere?

I have Googled around a bit, and found a few threads on
the subject, but they all seem to fizzle out.

(e.g. : INPUT 35, OUTPUT "100011" )
 
M

Mensanator

Thanks for that. The offerings are very similar to the
algorithms I wrote myself.

It wasn't the solution I was after,really; that's
easy. It was whether anything had found its way into
the standard library.

Isn't that coming in Python 3.0?

You could also use gmpy, which has a lot of
other bit-functionality in addition to displaying
them.
print 'i:',gmpy.digits(i,2).zfill(8),
print '# of 1-bits:',gmpy.popcount(i),
print 'find LS 1-bit:',gmpy.scan1(i),
print 'bit difference:',gmpy.hamdist(i,2**8-1)


i: 00000000 # of 1-bits: 0 find LS 1-bit: -1 bit difference: 8
i: 00000001 # of 1-bits: 1 find LS 1-bit: 0 bit difference: 7
i: 00000010 # of 1-bits: 1 find LS 1-bit: 1 bit difference: 7
i: 00000011 # of 1-bits: 2 find LS 1-bit: 0 bit difference: 6
i: 00000100 # of 1-bits: 1 find LS 1-bit: 2 bit difference: 7
i: 00000101 # of 1-bits: 2 find LS 1-bit: 0 bit difference: 6
i: 00000110 # of 1-bits: 2 find LS 1-bit: 1 bit difference: 6
i: 00000111 # of 1-bits: 3 find LS 1-bit: 0 bit difference: 5
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top