[英]Put string on byte-like object in python
I have a problem with concatenating two encoded strings in python.我在连接 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:但我想动态地将 append \x97\x15
部分字符串传递给它,我的解决方案如下:
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.但是这个a
和b
变量不一样,我计算了a
和b
的 hash 并且它们不一样。 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
. convert()
function 用于将数字转换为十六进制并将十六进制的每一部分反转,例如5527
的十六进制是0x1597
我应该在这个 function 中收到\x97\x15
并将其放在字符串的中间a
。 is there another way to convert 5527
to \x97\x15
and put it in the middle of the string a
?还有另一种方法可以将5527
转换为\x97\x15
并将其放在字符串a
的中间吗?
Your convert function is incorrect, and this is because a general confusion about \x97\x15 :您的转换function 不正确,这是因为对\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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.