![](/img/trans.png)
[英]Hello, i have a text file that i want to write in UTF-16 unicode using python
[英]How to read and write "Unicode (UTF-16 little endian)" text to and from a binary file in Python?
我有一个二进制文件“x.bin”,它是一个 Windows 可执行文件。
我正在尝试使用 Python 修改此可执行文件中的字符串值,在文本编辑器中查看此字符串 我被告知文本编码为“Unicode(UTF-16 little endian)”,我可以看到空字节环绕字符串中的文本。
但是,当我尝试在 Python 中以二进制模式读取该文件并将其转换为十六进制时,我被告知在执行print("10002000" in _hex)
时文件中不存在十六进制,因此无法替换任何数据。
我也无法使用encoding="utf-16-le"
以"r"
模式访问文件,因为这会尝试解码数据并且会失败。
有没有办法在 Python 中使用 UTF-16 编码访问二进制数据?
编辑:
_hex 是调用 data.hex() 后的结果
我正在使用这种方法从文件中读取
with open("resources\\rfreeze.bin", "rb") as f:
data = f.read()
您的问题有点不清楚,但要编辑可执行文件,您只需将目标字节替换为另一组相同长度的字节。 这是一个例子:
test.c - 带有嵌入式 UTF-16LE 字符串的简单程序(无论如何,在 Windows 中):
#include <stdio.h>
int main() {
wchar_t* s = L"Hello";
printf("%S\n",s);
return 0;
}
test.py - 用另一个字符串替换字符串
with open('test.exe','rb') as f:
data = f.read()
target = 'Hello'.encode('utf-16le')
replacement = 'ABCDE'.encode('utf-16le')
if len(target) != len(replacement):
raise RuntimeError('invalid replacement')
data = data.replace(target,replacement)
with open('new_test.exe','wb') as f:
f.write(data)
演示:
C:\>cl /W4 /nologo test.c
test.c
C:\>test.exe
Hello
C:\>test.py
C:\>new_test.exe
ABCDE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.