I am talking to a piece of a test equipment using a serial interface. The two letter ascii ID of the device is encoded as a base 10 integer in a specific register. Each pair of integers needs to be converted to an ascii character. My question is what is the best way to do this conversion. I used the method below but it seems fairly complicated for a such a simple task.
Example
input: 5270
Desired output: '4F'
(ascii values of 52 and 70)
get the raw register value
>>> result =f4.read_register(0,)
>>> result
5270
convert the integer into a list of chars
>>> chars = [i for i in str(result)]
join the pairs together
>>> pairs = [''.join((chars[x], chars[x+1])) for x in xrange(0,len(chars),2)]
>>> pairs
['52', '70']
>>> pairs = [chr(int(x)) for x in pairs]
>>> pairs
['4', 'F']
Add a bit of maths.
/
- Integer division%
- Modulus operatorCode
And to match desired output