简体   繁体   中英

Put string on byte-like object in python

I have a problem with concatenating two encoded strings in python. Below string is which I want to have after concatenating:

a = b"\x50\x02\x00\x00\x00\x00\x97\x15\x0d\x00\x00\x00\x00\x00\x00\x8d\x0a"

But i want to dynamicly append \x97\x15 part of string to it, my solution is like below:

def convert(deviceId):
        return r"\x{}\x{}".format(str(hex(int(deviceId))).replace("0x", "")[2:].strip(), str(hex(int(deviceId))).replace("0x", "")[:2].strip())

b = "\x50\x02\x00\x00\x00\x00{}\x0d\x00\x00\x00\x00\x00\x00\x8d\x0a".format(convert(5527))

but this a and b variables are not the same, i calculate the hash of a and b and they are not the same. How can I fix this? The convert() function is used to convert a number to hex and reverse each piece of the hex, for example, the hex of 5527 is 0x1597 and I should receive \x97\x15 in this function and put it in the middle of the string a . is there another way to convert 5527 to \x97\x15 and put it in the middle of the string a ?

Your convert function is incorrect, and this is because a general confusion about \x97\x15 :

  1. What it actually is: the hex representation of 5527 - 2 bytes in big endian order ( 0x97 , 0x15 ), or characters with the ASCII codes: 151, 21
  2. What you think it is: the "stringized" form of the above (what repr would return) - an 8 byte string with the following char s: ' \ ', ' x ', ' 9 ', ' 7 ', ' \ ', ' x ', ' 1 ', ' 5 '
 >>> def convert_orig(deviceId): ... return r"\x{}\x{}".format(str(hex(int(deviceId))).replace("0x", "")[2:].strip(), str(hex(int(deviceId))).replace("0x", "")[:2].strip())... >>> >>> co = convert_orig(5527) >>> co, len(co) ('\\x97\\x15', 8) >>> >>> def convert_new(device_id): # Does NOT work for numbers wider than 2 bytes (greater than 65536)... return "".join(chr(i) for i in reversed(divmod(device_id, 256)))... >>> cn = convert_new(5527) >>> cn, len(cn) ('\x97\x15', 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