convert integer to binary
Dan Bishop
danb_83 at yahoo.com
Fri May 2 23:49:09 EDT 2003
Jan Olderdissen <jolderdissen at ixiacom.com> wrote in message news:<u8n5bvo6ks4lg757ujptg6i5v2v0gpsk08 at 4ax.com>...
> >I couldn't find any function in Python to convert integers to binary
> >and vice versa, for example:
>
> Try int ("1111", 2) to go from binary to integer. For the reverse
> direction, you'll probably have to implement a couple of lines of
> actual code. :-)
I've implemented such a function in only one line before, but here's
the readable version, plus 3 related functions.
# ------------ baseconv.py ------------
from __future__ import division
import string, math
digits = string.digits + string.uppercase
def atoi(s, radix=10):
"the integer represented by the string s in the given base"
try:
return int(s, radix)
except OverflowError:
return long(s, radix)
def atof(s, radix=10):
"the float represented by the string s in the given base"
if s[0] == '-':
return -atof(s[1:], radix)
decimalPointIndex = s.find('.')
if decimalPointIndex < 0:
return float(atoi(s, radix))
iPart = atoi(s[:decimalPointIndex], radix)
fPart = s[decimalPointIndex+1:]
if fPart:
fPart = atoi(fPart, radix) / radix ** len(fPart)
else:
fPart = 0
return iPart + fPart
def itoa(num, radix=10):
"the string representing the integer num in the given base"
if num == 0:
return '0'
isNegative = num < 0
if isNegative:
num = -num
d = []
while num > 0:
num, lastDigit = divmod(num, radix)
d.append(digits[lastDigit])
if isNegative:
d.append('-')
d.reverse()
return ''.join(d)
def ftoa(num, radix=10):
"the string representing the float num in the given base"
if num < 0:
return '-' + ftoa(num, radix)
significantDigits = int(math.ceil(52 * math.log(2) /
math.log(radix)))
leftDigits = int(math.log(num) / math.log(radix) + 1)
decimalPlaces = max(significantDigits - leftDigits, 0)
scaledNum = long(num * radix ** decimalPlaces + 0.5)
iPart, fPart = divmod(scaledNum, radix ** decimalPlaces)
iPart = itoa(iPart, radix)
fPart = string.zfill(itoa(fPart, radix), decimalPlaces)
s = "%s.%s" % (iPart, fPart)
lastDigitPosition = len(s) - 1
while s[lastDigitPosition] == digits[0]:
lastDigitPosition -= 1
return s[:lastDigitPosition+1]
More information about the Python-list
mailing list