Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting from binary to String

In Python, I have been able to take in a string of 32 bits, and convert this into a binary number with the following code:

def doConvert(string):
    binary = 0
    for letter in string:
        binary <<= 8
        binary += ord(letter)

    return binary

So for the string, 'abcd', this method will return the correct value of 1633837924, however I cannot figure out how to do the opposite; take in a 32 bit binary number and convert this to a string.

If someone could help, I would appreciate the help!

like image 257
andrewvincent7 Avatar asked Nov 18 '15 00:11

andrewvincent7


1 Answers

If you are always dealing with a 32 bit integer you can use the struct module to do this:

>>> import struct
>>> struct.pack(">I", 1633837924)
'abcd'

Just make sure that you are using the same endianness to both pack and unpack otherwise you will get results that are in the wrong order, for example:

>>> struct.pack("<I", 1633837924)
'dcba'
like image 75
shuttle87 Avatar answered Oct 06 '22 20:10

shuttle87