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!
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With