[Tutor] Binary
Remco Gerlich
scarblac@pino.selwerd.nl
Sat, 12 May 2001 06:38:20 +0200
On 0, "Timothy M. Brauch" <tbrauch@mindless.com> wrote:
> Okay, I know hex(x) will display x in hexadecimal and oct(x) will
> display x in octal, but how do I display x in binary? I've tried
> seraching the python docs, but a search on binary turns up more on
> binary distributions and a search on base turns up stuff about base
> classes.
I like this method. It does keep some leading 0s:
_bindict = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
'd': '1101',
'e': '1110',
'f': '1111'
}
def bin(x):
import string
h = hex(x)[2:] # Skip the '0x' bit
string.join(map(_bindict.get, h), "")