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 :
>>> 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.