[英]How to modify an hexadecimal string bytes by bytes in Python?
I'm programming a little piece of code to swap headers between .bmp and .wav files. 我正在编写一小段代码来交换.bmp和.wav文件之间的标头。 I managed to extract raw bytes (eg \\x00\\x12
) and transform it into a string ( 0012
) but what I wanna do now is split the string in a way that I can modify it two bytes by two bytes. 我设法提取原始字节(例如\\x00\\x12
)并将其转换为字符串( 0012
)但我现在要做的是以一种方式拆分字符串,我可以将它修改为两个字节乘以两个字节。 This means that I have my hex string, for example FACB3D52
, and I want it to be split out FACB
so that I can apply rules in it (if there is A, replace by B), and then it moves forward to 3D52
, apply the same rules, and reassemble the string so that it outputs FBCB3D52
这意味着我有我的十六进制字符串,例如FACB3D52
,我希望它被拆分为FACB
以便我可以在其中应用规则(如果有A,替换为B),然后它向前移动到3D52
,应用相同的规则,并重新组合字符串,以便输出FBCB3D52
I do not have much experience in Python and I really have no clues on how I should go for this problem 我没有太多的Python经验,我真的没有关于如何解决这个问题的线索
If you are applying the same rule to each chunk of the hexadecimal number, you can use the following. 如果要对十六进制数的每个块应用相同的规则,则可以使用以下内容。
hexstr = "FACB3D52"
hexlist = [hexstr[i:i+4] for i in range(len(hexstr)//4)] # Split into list of substrings
new_hexlist = [substr.replace('A', 'B') for substr in hexlist] # Apply rule to each substring
new_hexstr = ''.join(new_hexlist) # Join substrings back to form final string
print(new_hexstr)
Output 产量
FBCBBCB3 FBCBBCB3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.