简体   繁体   English

将字符串放在 python 中的字节状 object

[英]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.但是这个ab变量不一样,我计算了ab的 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的普遍混淆:

  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它实际上是什么: 5527 - 2 个字节的大端顺序( 0x970x15 )的十六进制表示,或具有ASCII码的字符: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 '你认为它是什么:上面的“字符串化”形式( repr将返回) - 一个 8 字节字符串,带有以下字符:' \ '、' 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM