How do I convert 32b (four characters) from an int value to an ASCII string in python

375 Views Asked by At

Hi I have a 32b value that I need to easily truncate in to it's four bytes, convert each byte to ASCII and combine them to a four letter string. And I also need the reverse process. I have been able to do this in one direction in the following ugly way:

## the variable "binword" is a 32 bit value read directly from an MCU, where each byte is an 
## ASCII character

char0 = (binword & 0xFF000000) >> 24
char1 = (binword & 0xFF0000) >> 16
char2 = (binword & 0xFF00) >> 8
char3 = (binword & 0xFF)

fourLetterWord = str(unichr(char0))+str(unichr(char1))+str(unichr(char2))+str(unichr(char3))

Now, I find this method really un-elegant and time consuming, so the question is how do I do this better? And, I guess the more important question, how do I convert the other way?

1

There are 1 best solutions below

0
On BEST ANSWER

You should use the struct module's pack and unpack calls for these convertions

number = 32424234

import struct
result = struct.pack("I", number)

and back:

 number = struct.unpack("I", result)[0]

Please, refer to the official docs on the struct module for the struct-string syntax, and markers to ensure endiannes, and number size. https://docs.python.org/2/library/struct.html

On a side note - this is by no way "ASCII" - it is a bytestring. ASCII refers to a particular text encoding with codes on the 32-127 numeric range. The point is that you should not think on bytestrings as text, if you need a stream of bytes - and much less think of "ASCII" as an alias for text strings - as it can represent less than 1% of textual characters existing in the World.