简体   繁体   中英

Python convert HEX number digits ASCI representation into string

I want to make function doing exactly this:

#This is my imput number
MyNumberDec = 114
MyNumberHex = hex(MyNumberDec)

print (MyNumberDec)
print (MyNumberHex)

#Output looks exactly like this:
#114
#0x8a

HexFirstDigitCharacter = MagicFunction(MyNumberHex)
HexSecondDigitCharacter = MagicFunction(MyNumberHex)
#print (HexFirstDigitCharacter )
#print (HexSecondDigitCharacter )

#I want to see this in output
#8
#A

What is that function?

Why I need this? For calculating check-sum in message sending towards some industrial equipment

For example command R8:

N   |   HEX |   ASC
1       52      R
2       38      8
3       38      8   
4       41      A

Bytes 1 and 2 are command, bytes 3 and 4 are checksum Way of calculating checksum: 0x52 + 0x38 = 8A I have to send ASCII 8 as third byte and ASCII A as fourth byte

Maybe I dont need my magicfunction but other solution?

You can convert an integer to a hex string without the preceding '0x' by using the string formatter:

MyNumberDec = 114
MyNumberHex = '%02x' % MyNumberDec
print(MyNumberHex[0])
print(MyNumberHex[1])

This outputs:

7
2

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