ASCII to HEX conversion

sam westernsam at hotmail.com
Fri Apr 12 07:56:27 EDT 2002


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



More information about the Python-list mailing list