#General routines for manipulating sequences of byte data, including converting #to and from ASCII representation, and displaying result as a hex string or a binary #string. #Note that these functions are not especially helpful below the byte level, if you have #to, say concatenate sequences of fewer than 8 bits and convert back to a numerical value. #We may address this in future modules. #bin8 #if 0<=val<256 return a length 8 string that is the ASCII representation #with leading 0s ( return value is garbage or an error otherwise) import base64 def bin8(val): s=bin(val) leadingz='0'*(10-len(s)) return leadingz+s[2:] #hex2 #do the same thing for hex conversion, returning two hex digits for values #in the range 0<=val<256 def hex2(val): s=hex(val) leadingz='0'*(4-len(s)) return leadingz+s[2:] #ascii_to_bytes #Take an ASCII string and return a list of byte values def ascii_to_bytes(instring): return [ord(c) for c in instring] #bytes_to_ascii #Inverse of the above. If a list item is a non-printing character, you probably don't #want to use this and should try something like bytes_to_hex below or bytes_to_b64 below. If the #list item is outside the range 0 to 255, then chr will throw an error def bytes_to_ascii(bytelist): s='' for b in bytelist: s += chr(b) return s #bytes_to_hex #returns a string giving the hexadecimal representation of each byte in the #sequence, separated by spaces def bytes_to_hex(bytelist): result='' for b in bytelist: result+=hex2(b)+' ' return result def hex_to_long(hexstring): u='' for j in hexstring: if j!=' ': u+=j return long(u,16) def hex_to_bytes(hexstring): return long_to_bytes(hex_to_long(hexstring)) def hex_to_ascii(hexstring): return bytes_to_ascii(hex_to_bytes(hexstring)) #bytes_to_bin #same as the above in binary rather than hex def bytes_to_bin(bytelist): result='' for b in bytelist: result+=bin8(b)+' ' return result #bytes_to_b64 #returns the standard base64 encoding of the sequence of bytes def bytes_to_b64(bytelist): return base64.b64encode(bytes_to_ascii(bytelist)) #b64_to_bytes #we can also decode the b64 representation def b64_to_bytes(b64string): return ascii_to_bytes(base64.b64decode(b64string)) #take a long integer and convert it to a sequence of bytes, beginning with #most significant byte def long_to_bytes(bignum): s=[] while bignum != 0: s.append(int(bignum%256)) bignum /= 256 s.reverse() return s def bytes_to_long(bytelist): bignum=0 for by in bytelist: bignum = 256*bignum+by return bignum #getbit #Extract bit j from a byte. Bits are numbered from 0 for least significant to 7 for most significant. def getbit(b,j): return (b&(1<>j #xor #One of our two basic operations on bit strings. The other is concatenation, which in Python is #simply addition of lists. #requires len(bytelist1)<=len(bytelist2) def xor(bytelist1,bytelist2): length=len(bytelist1) return [bytelist1[j]^bytelist2[j] for j in range(length)]