简体   繁体   中英

String to hex value of FF in python 2.7

I know this is a basic question, but I am really struggling to work it out.

I am trying to get a string to convert to FF in hex (ie OxFF) in python 2.7.

I convert the string to bytearray then to hex using the following code:

>>> data = 'OxFF'
>>> array = bytearray(data)
>>> print binascii.hexlify(array)
4f784646

For context, I am sending a message over TCP/IP using twisted and the header needs to be FF FF

Any help would be amazing.

Cheers

You can create directly the header as a string literal:

>>> header = '\xff\xff'
>>> hedaer
'\xff\xff'

Converting from data :

>>> data = '0xFF'
>>> binascii.unhexlify(data[2:])
'\xff'

The key is to skip over the 0x prefix.

Or as an integer:

>>> int(data, 16)
255

where 255 is 0xFF of course.

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