Python 3:无法将二进制数据转换为文本

时间:2019-05-06 12:50:06

标签: python binary hex

在我的一个项目中,我想传输一个二进制文件,该文件是微控制器的固件:“ firmware.bin”。看起来像这样:

  

007c 0020 4da0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000   49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000   49a0 0000 49a0 0000 49a0 0000 018a 0000 49a0 0000 bd82 0000 058a 0000   098a 0000 7182 0000 118a 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000   49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000   49a0 0000 49a0 0000 49a0 0000 49a0 0000 49a0 0000 ...

将内容打印在我称为检索数据的URL上。在URL上,它将转换为文本,如下所示:

  

。||。   M.I.I.I.I.I.I.I.I.I.I.I.I.I.I.I.I. ������������������������������������������������������������������� 我...我...我...我...我...我...我...我...我...我...我...我...

...

当我读回它时,得到以下内容:

  

007c 0020 4def bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd 0000   49ef bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd   0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef   bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 01ef bfbd 0000 49ef bfbd 0000   efbf bdef bfbd 0000 05ef bfbd 0000 09ef bfbd 0000 71ef bfbd 0000 11ef   bfbd 0000 49ef bfbd 0000 49ef bfbd 0000 49ef bfbd

与我一开始的情况不同。

这是代码:

# download the data
r = requests.get(URL);

# save it to bin file
data = r.text.encode('utf-8')
f.write(bytes(data))

你知道我在做什么错吗?

编辑

我找到了解决方案。我正在使用 echo file_get_contents($ file)在PHP程序中打印二进制文件。好像它剪切了一些字符,例如0x00 ...所以现在我在使用: echo bin2hex(file_get_contents($ file)),在我的Python程序中检索字符串中的完整数据并将其转储到具有 f.write(bytes.fromhex(data))

的文件

0 个答案:

没有答案
相关问题