Done (sortof) - (was Newbie: displaying binary numbers?)

Steven Adams adams_s at lab.eng.usyd.edu.au
Mon Jun 12 02:11:33 EDT 2000


there is probably a cleaner method in the modules already, but this seems to
work fine.

I converted any numbers to hex. then turned the hex into a string, for each
letter in the string, there is a corresponding 4 bit sequence.
####

hexvals={'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 int2binary(num):
                     "int2binary( num, bits ): display 'num' as a binary
with 'bits' number of bits"
                     s=str( hex( num ) )
                     s=s[2:]
                     b=''
                     for i in s:
                                b=b+hexvals[i]
                     return b

#is this right, it seems to work.

now, whats the best way to go about converting back to a normal base 10
representation?
I'd thought of just quickly breaking the string of 1's and 0's into strings
4 chars long, then using another lookup table.




Steven Adams <adams_s at lab.eng.usyd.edu.au> wrote in message
news:8i1q49$2nk3$1 at news1.wire.net.au...
> Hi all,
>
> I'm trying to display integers as binary numbers, I know there are the
calls
> for making hexadecimal and octal strings, but couldn't find anything for
> binary?
>
> are there any modules, or operations not in the docs?
>
> all I need is to convert a number to a binary with n bits.
>
> thanks, Steven
>
>





More information about the Python-list mailing list