7

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!

3
  • @shuttle87 I'm using Python2 Commented Nov 18, 2015 at 0:15
  • Is it always a 32bit integer? Commented Nov 18, 2015 at 0:17
  • yeah always a 32bit string being converted. Commented Nov 18, 2015 at 0:18

1 Answer 1

6

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'
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this works really well! What does the argument, ">I" do? I can't find a reasonable explanation in the docs.
The I says that it is an unsigned integer. The > says that it is in big-endian format.
>>> help(struct) The optional first format char indicates byte order, size and alignment: @: native order, size & alignment (default) =: native order, std. size & alignment <: little-endian, std. size & alignment >: big-endian, std. size & alignment !: same as >
help(struct) is a good idea! Also the struct documentation has a table with the possible formats.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.