""" Useful functinons. """ import string import types # ================================================== # # ================================================== def bitToInt (bitString, bitOrder=0) : """ A string or list is interpreted as a binary number(0's and 1's) and translated into a integer number. example: *i* = *bitToInt* ("100100") would set *i* to 36 (0x24). """ if type(bitString) == types.StringType : oneBit = '1' else : oneBit = 1 intValue = 0 msb = len(bitString) - 1 for bit in bitString : if bit == oneBit: intValue |= 0x1 << msb msb -= 1 return intValue def bitToIntLSB(bitString, bitOrder=0) : """ A string or list is interpreted as a binary number(0's and 1's) and translated into a integer number. The first element in the list(string) is the LSB. example: *i* = *bitToIntLSB* ("100100") would set *i* to 9 (0x09). """ if type(bitString) == types.StringType : oneBit = '1' else : oneBit = 1 intValue = 0 lsb = 0 for bit in bitString : if bit == oneBit: intValue |= 0x1 << lsb lsb += 1 return intValue # ================================================== # # ================================================== def intToBitStr (value) : """ Represent the bits of the integer *value* as a string of 0'1 and 1's. example: *intToBitString* (4) returns '0000 0000 0000 0000 0000 0000 0000 0100' """ bitStr = 32 * ['0'] for i in xrange(32) : if (value >> i) & 0x1 : bitStr[31-i] = '1' for i in range(4,36,5) : bitStr.insert(i," ") return string.join(bitStr,"") def intToBitList (value, width=32, msb=1) : """ Represent the bits of the integer *value* as a List of 0'1 and 1's. example: *intToBitString* (4,7) returns [0,0,0,0,1,0,0] \n example: *intToBitString* (23,4) returns [0111] \n example: *intToBitString* (1,3,1) returns [0,0,1] \n example: *intToBitString* (1,3,0) returns [1,0,0] \n The length of the list is *width*. Only the *width* least significant bits of *value* are used. if *msb* = 1, the MSB is the most left entry in the list, otherwise the LSB is most left bit in the returned list. """ bitStr = width * [0] if msb : for i in range(width) : if (value >> i) & 0x1 : bitStr[width-1-i] = 1 else : for i in range(width) : if (value >> i) & 0x1 : bitStr[i] = 1 return bitStr