Integer to "binary string"?
Jeff Epler
jepler at unpythonic.net
Sun Dec 15 15:43:06 EST 2002
> s = (i & 1 and '1' or '0') + s
This is the same as
if i % 2 == 1: # i mod 2
s = '1' + s
else:
s = '0' + s
("x & (n-1)" is the same as "x % n" if n is a power of 2)
("a and b" is a if a it is false, otherwise it is b.
"c and d" is c if c is true, otherwise it is d.
"a and b or c" is equivalent to C's "a ? b : c" as long as b is not false.
"a ? b : c" is like "if a: b; else c" except that it is an expression,
not a statement)
> i >>= 1
This is the same as
i = i / 2 # truncating ("floor") division
( x >> n is the same as x / (2^n) )
> return s or '0'
This is the same as
if s:
return s
else:
return 0
So this code simply follows the rule to convert a number into any base:
If the number is 0, return '0'
Otherwise, find the leftmost digit by taking the remainder of the number
divided by the base. Then, for purposes of finding the rest of the
digits, divide the number by the base and continue.
A more generic version might read like this (good for bases up to 26):
digit_names = string.digits + string.uppercase[:26] # "0..9A..Z"
def convert_to_base_n(number, base):
if number == 0: return "0"
converted_number = ""
while number:
number, digit = divmod(number, base)
converted_number = digit_names[digit] + converted_number
return converted_number
divmod(a,b) is equivalent to (a/b, a%b), when a and b are both positive.
To convert from any base, you can use int("...", base):
>>> int("1001", 2)
9
you could write this yourself:
character_to_digit = dict([(digit_names[i], i)
for i in range(len(digit_names))])
def convert_from_base_n(converted_number, base):
number = 0
for converted_digit in converted_number:
number = number * base + character_to_digit[converted_digit]
return number
This is all basic "base" arithmetic. It should all be clear once the
cleverness in Python implementation is stripped away. The example you
found visits some slightly odd corners of Python. We're not totally immune
to the urge to appear clever when we write our code.
Jeff
More information about the Python-list
mailing list