Best way to Convert pairs of base 10 integers to ascii characters in python

827 views Asked by At

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']
2

There are 2 answers

4
Bhargav Rao On BEST ANSWER

Add a bit of maths.

  • / - Integer division
  • % - Modulus operator

Code

>>> num = 5270
>>> pairs = [chr(num/100),chr(num%100)]
>>> pairs
['4', 'F']

And to match desired output

>>> ''.join(pairs)
'4F'
5
dting On

In addition to @BhargavRao answer, you can use the divmod builtin:

num = 5270
''.join(map(chr, divmod(num, 100)))

# '4F'

You can also use string formatting:

'{:c}{:c}'.format(*divmod(num, 100))

# '4F'