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 I'm using Python2andrewvincent7– andrewvincent72015年11月18日 00:15:16 +00:00Commented Nov 18, 2015 at 0:15
-
Is it always a 32bit integer?shuttle87– shuttle872015年11月18日 00:17:31 +00:00Commented Nov 18, 2015 at 0:17
-
yeah always a 32bit string being converted.andrewvincent7– andrewvincent72015年11月18日 00:18:17 +00:00Commented Nov 18, 2015 at 0:18
1 Answer 1
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'
4 Comments
>>> 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.