简体   繁体   中英

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

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

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'

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM