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!

shuttle87's user avatar
shuttle87
16.1k12 gold badges80 silver badges107 bronze badges
askedNov 18, 2015 at 0:10
andrewvincent7's user avatar
3
  • @shuttle87 I'm using Python2CommentedNov 18, 2015 at 0:15
  • Is it always a 32bit integer?CommentedNov 18, 2015 at 0:17
  • yeah always a 32bit string being converted.CommentedNov 18, 2015 at 0:18

1 Answer1

6

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

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

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

>>> struct.pack("<I", 1633837924)'dcba'
answeredNov 18, 2015 at 0:18
shuttle87's user avatar
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.
TheI says that it is an unsigned integer. The> says that it is inbig-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 thestruct documentation has a table with the possible formats.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.