Binary to Hex conversions

Alex Martelli alex at magenta.com
Fri Aug 18 11:55:48 EDT 2000


"Mike Olson" <mro at provis.com> wrote in message
news:8njggb$sbr$1 at nnrp1.deja.com...
> How do I convert a binary number to a decimal or hex number?

In Python, 'numbers' are distinguished as 'integer', 'long-integer',
etc, not as 'binary', 'decimal', 'hex'; in other words, "a number is
a number" (except it can be a number of any of various _types_) and
does not carry information about the base in which it's represented.

If you do have a _number_, say an integer for example, you can
transform it into a _string_ representing it in various bases:

PythonWin 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Portions Copyright 1994-2000 Mark Hammond (MHammond at skippinet.com.au)
>>> x=23
>>> hex(x)
'0x17'
>>> oct(x)
'027'
>>>

I don't know of any ready-made Python way to convert a number to
a string representing it in an _arbitrary_ base (a strange omission,
but I may be simply forgetting something...!).  It's not too
difficult to write in Python, fortunately:


import string

def toBase(x, base):
    if not x: return '0'
    digits=[]
    minus=''
    if x < 0:
        minus='-'
        x=-x
    while x:
        x, digit = divmod(x, base)
        digits.append(str(digit))
    if minus: digits.append(minus)
    digits.reverse()
    return string.join(digits,'')

>>> toBase(23,2)
'10111'
>>>


If you start with a string, and you know it represents a number
in an arbitrary base (say, base 2 -- maybe that's what you mean
by "a binary number", a string which is a base-2 representation
of some integer...), then you CAN convert the string into a
number with a Python-provided function:

>>> import string
>>> string.atoi('10111',2)
23
>>>


So, if your question means: starting with a string that is a
base-2 representation of some number, how can I get the string
that is the base-10 or base-16 representation of the same
number; then one solution might be:

import string

def binary2other(thebinary, transform=str):
    return transform(string.atoi(thebinary,2))

>>> binary2other('10111')
'23'
>>> binary2other('10111',hex)
'0x17'
>>>


Alex






More information about the Python-list mailing list