ASCII to HEX conversion
Bengt Richter
bokr at oz.net
Fri Apr 12 15:43:57 EDT 2002
On 12 Apr 2002 04:56:27 -0700, westernsam at hotmail.com (sam) wrote:
>The following code will give binary from decimal. (N.B. I cannot claim
>credit for this as I didn't write it and just found it somewhere)
>
>import math, operator
>
>def binary_repr(self, number, max_length = 32):
> assert number < 2L << max_length
> shifts = map (operator.rshift, max_length * [number], range
>(max_length - 1, -1, -1))
> digits = map (operator.mod, shifts, max_length * [2])
> if not digits.count (1): return "00000000"
> digits = digits [digits.index (1):]
> returnString = string.join (map (repr, digits), '')
> while (len(returnString) < 8):
> returnString = "0%s" % returnString
> return returnString
A little less importing etc:
>>> def binstr(n, maxbits=None):
... absn = abs(n)
... s=[chr(((n>>b)&1)+48) for b in xrange(maxbits or len(hex(n))*4)
... if maxbits or absn>>b or not b or (n<0 and absn>>(b-1))]
... s.reverse()
... return ''.join(s)
...
>>> binstr(1)
'1'
>>> binstr(0)
'0'
>>> binstr(1,8)
'00000001'
>>> binstr(0xaaaaaaaa)
'10101010101010101010101010101010'
>>> binstr(0xcccc, 32)
'00000000000000001100110011001100'
>>> binstr(-1L<<55)
'110000000000000000000000000000000000000000000000000000000'
>>> binstr( 1L<<55,57)
'010000000000000000000000000000000000000000000000000000000'
>>> binstr(-5)
'1011'
>>> binstr(-5,8)
'11111011'
>>> binstr(-5,2)
'11'
Note that I preserved a sign bit as such instead of generating the bits
of the absolute value with a minus sign. This makes an ambiguity, but it
shows the bits of the negative value. You can easily change it as desired.
Regards,
Bengt Richter
More information about the Python-list
mailing list