binary to decimal conversion

Jeff Pinyan jeffp at crusoe.net
Mon Mar 27 20:04:23 CEST 2000


[posted & mailed]

On Mar 27, ezra said:

>def Int2Bin(di):
>     chars = ['0','1']
>     do = ''
>     q = 0
>     while di >= 2:
>          q = di % 2
>          do = chars[q] + do
>          di = di / 2
>     do = chars[di] + do
>     if len(do)%4 >= 1 and len(do)%4 <= 3 : do = '0'*(4 - len(do)%4) + do
>     return do
># End of def Int2Bin(di)

Hmm.

>def Int2Oct(di):
[snip]
>def Int2Hex(di):
[snip]

Why make these two functions?  Python offers a (s)printf like formatting
for strings:

>>> a = "%o" % 100
>>> a
'144'
>>> a = "%x" % 100
>>> a
'64'

They're strings.  Do with them what you will.

Personally, I think it is monumentally easier to convert an octal number
to binary, than a decimal number.

Here's my stab at it:

def dec2bin (val):
  val = "%o" % val  # we like octal
  ret = ""
  for i in range(len(val)):  # yes, I'm using index instead of value
    byte = int(val[i])
    bit = 0

    # bitwise operations are fun
    if byte & 1: bit = 1
    if byte & 2: bit = 10*bit + 1
    if byte & 4: bit = 100*bit + 1

    if i != len(val) - 1: bit = "%03d" % bit  # this is why I use index
    else: bit = `bit`

    ret = bit + ret
  return ret

-- 
MIDN 4/C PINYAN, NROTCURPI, US Naval Reserve             japhy at pobox.com
http://www.pobox.com/~japhy/                  http://pinyaj.stu.rpi.edu/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/




More information about the Python-list mailing list