简体   繁体   中英

Convert a string of escaped hex to a hex number in Python

How do I convert a string of escaped hex characters to a single hex number?

Reading from a socket I get a string of \\xFF\\xFF\\xFF.., etc. I want to convert this to a hex number, 0xFFFFFF, keeping any insignificant 0s, so \\x00\\xFF should be 0x00FF. I have tried various functions from binascii, but I have not had any luck.

Using struct.unpack :

>>> struct.unpack('>I', '\xFF\xFF\xFF\xFF')  # >, !: big (network) endian
(4294967295,)
>>> hex(struct.unpack('>I', '\xFF\xFF\xFF\xFF')[0])
'0xffffffff'

>>> struct.unpack('>H', '\x00\xff')
(255,)
>>> '0x{:04x}'.format(struct.unpack('>H', '\x00\xff')[0])
'0x00ff'
>>> '0x{:04X}'.format(struct.unpack('>H', '\x00\xff')[0])
'0x00FF'

Format characters used:

  • I : 4-bytes unsigned int
  • H : 2-bytes unsinged int

UPDATE

If you indent to convert arbitrary binary string into hex string, you can use binascii.hexlify :

>>> import binascii
>>> '0x' + binascii.hexlify('\xFF\xFF\xFF')
'0xffffff'
>>> '0x' + binascii.hexlify('\x00\x00\xFF')
'0x0000ff'

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