简体   繁体   中英

Python 2.7: how to prevent automatic decoding from hex to string

I'm working with the python socket module, playing around with a udp client I wrote. I dislike how its handling my hex literals. example:

>>> querydns = '\xb9\x1b\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03\x77\x77\x77\x06\x67\x6f\x6f\x67\x6c\x65\x03\x63\x6f\x6d\x00\x00\x01\x00\x01'
>>> querydns
'\xb9\x1b\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'

>>> replydata
'\xb9\x1b\x81\x80\x00\x01\x00\x06\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0j\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0i\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0\x93\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0g\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0h\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xd4\x00\x04@\xe9\xb0c'

Notice how it automatically decodes some of the hex into characters? I want to deal with only hex values, no @'s or www's. Is there an easy way to stop this automatic decoding?

you cant really ... you have a few options(sort of)

import binascii
print binascii.hexlify(querydns)

or fake it(it takes more effort to preserve leading zeros)...

print "".join("\\x%s"%(hex(ord(data_byte))[2:]) for data_byte in querydns)

or a combination I guess would work

hexy = binascii.hexlify(querydns)
print "".join("\\x%s"%hexy[i:i+2] for i in range(len(hexy)-1))

You can use it as 'raw' string by putting a 'r' before the string. A raw string is not processed by the python and is taken as it is.

string = r"example string"

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