My goal is to take any size number, and convert it to a string of smaller characters that represent the concatenation of the binary expansion of the number. To illustrate what I am talking about, here is an example using the number 4820
:
4820's binary: 0001001011010100 # 16 bits of binary, enough to store the number 4820 Separated: 00010010 11010100 # Simply split the binary into two char size pieces Characters: '\x12' 'Ô' # Converted the binary snippets into their respective characters Together: '\x12Ô' # The concatenation of the characters, this is what I need
I wrote a algorithm in Python to do the job for me, but I'm not sure if there is a easier way to do it, or if my algorithm is as efficient as it can be.
def to_chars(number, length): #takes number and expected binary length
string = bin(number)[2:] #built-in binary conversion
expanded = ('0' * (length - len(string))) + string #expand the binary
chars = ''
for pos in range(int(length / 8)): #iterates over chunks of 8 bits
section = expanded[8 * pos : 8 * (pos + 1)] #gets the binary snippet
chars += chr(int(section, 2)) #converts the binary into a character
return chars #return the concatenated string
There has to be a lower level, possibly built in way to do the same thing, but faster. In a way, this is just the conversion from one data type to another, but I can't figure out a faster way.
Here are a few benchmarks:
%timeit to_chars(4820, 16) 100000 loops, best of 3: 3.04 µs per loop %timeit to_chars(4820, 32) 100000 loops, best of 3: 4.6 µs per loop %timeit to_chars(690655640, 32) 100000 loops, best of 3: 4.59 µs per loop