简体   繁体   中英

Python convert string to bytes

Bear with me here guys, i am very begginer in Python. I would like to convert a string to bytes, actually doing it without any problem but having a problem on length of converted byte data.

Here is my string and its lenght is 36: mystring = "097845555220AC004C2E2C02000000000939"

I would like to convert this string to bytes with 18 length like this = byte_data = b'\x09\x78\x45\x55\x52\x20\xAC\x00\x4C\x2E\x2C\x02\x00\x00\x00\x00\x09\x39'

I have been doing like this and the result i have is 36 lenght of byte data.

mystring = "097845555220AC004C2E2C02000000000939"
byte_data = bytes(mystring, 'ascii')
print(byte_data) #b'097845555220AC004C2E2C02000000000939'
print(len(byte_data)) #24

Instead of 36 i would like to convert my string to 18 length byte data. Can you help me on this?

mystring = "097845555220AC004C2E2C02000000000939"
len(bytes.fromhex(mystring))

bytes.fromhex(...) converts a hex formatted string to a byte array. The string must respect the hex format. Otherwise you'll get an error.

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