These one-liner lambdas convert integers to binary strings with no leading zeros.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # bstr_pos: only positive integers
# zero -> ''
# negative -> ''
bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or ''
# bstr_nonneg: only non-negative integers
# zero -> '0'
# negative -> ''
bstr_nonneg = lambda n: n>0 and bstr_nonneg(n>>1).lstrip('0')+str(n&1) or '0'
# bstr_sgn: all integers, signed
# zero -> '0'
# negative get a minus sign
bstr_sgn = lambda n: n<0 and '-'+binarystr(-n) or n and bstr_sgn(n>>1).lstrip('0')+str(n&1) or '0'
# bstr: all integers
# zero -> '0'
# negative represented as complements, 16-bit by default
# optional second argument specifies number of bits
bstr = lambda n, l=16: n<0 and binarystr((2L<<l)+n) or n and bstr(n>>1).lstrip('0')+str(n&1) or '0'
|
I wanted to have a short cut-and-paste solution for representing integers as binary strings. As a result, these functions are by no means clear or readable.
The string concatenation method used here is quite slow. A faster approach would be to output digits directly to a file-like object, or maybe first construct a list and then make a string by joining it.
If you can use a data table, use octal conversion. If you define a table:
Then
might do the job. But I don't understand why:
is worse.
Binary with fixed length.
binary to decimal oneliner. Inverse of the previous...
I like bin() from Python 2.6, but it doesn't exist in Python 2.5. So I use this simple but inefficient replacement:
note that the list of lambdas [ ... ] can be replaced by a tuple of lambdas ( ... ) in my example
trying to print more than a few hundred bits at once using the recursive version is likely to exceed the maximum recursion depth. so here's a non-recursive version equivalent to the Python 2.6 bin() which should work all the way back to Python 2.3:
and here's a simplified version of the recursive version:
sorry, left one line out of place when reformatting for that post:
Here's another one: This one is better than most run time computation based methods, thanks to the efficient dictionary look up in Python: http://code.activestate.com/recipes/576847/