微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在二进制文件中从具有偏移量的输入写入字节?

如何解决如何在二进制文件中从具有偏移量的输入写入字节?

我试图用下面的脚本创建一个bin文件,该脚本应该从用户输入写入字节,并且在每个字符之间插入偏移字节。但是存在一个问题,它顺序地写入所有字节,并且在每个字节之后都没有分开,并且添加了用'shift'定义的偏移字节。

enter image description here

offset is 2 bytes    p        y        t        h        o        n
00000000 00000000 00110001 00110001 00110001 00110000 00110000 00110000 00110000 00000000 00000000 00000000

我希望它成为

offset 2 bytes      p      offset 2 bytes      y      offset 2 bytes        t    offset 2 bytes,etc
00000000 00000000 00110001 00000000 00000000 00110001 00000000 00000000 00110001 00000000 00000000 00110000 00000000 00000000 00110000 00000000 00000000 00110000 00000000 00000000 00110000 00000000 0000000

这是程序的代码

fdata = open("text.bin","wb")
fMeta = open("key.bin","w+b")
print('Enter text:')
txt='python' # input()
l=len(txt)
print(l,'bytes')
strtobin= ' '.join(format(x,'b') for x in bytearray(txt,'utf-8'))
print(strtobin)

# even bytes in key [xor 1]
for v in range(0,25,2):
    #print(v)
    fMeta.seek(v)
    fMeta.write(bytes(0))

shift=int(2)
sh=shift.to_bytes(1,byteorder='big')
# odd bytes in key 
for a in range(1,25):
    if a % 2 != 0:
        #print(a)
        fMeta.seek(a)
        fMeta.write(sh)

# text bin [xor 2]
pos=0
#for i in range(1,10): #(len(txt)+10)
for elem in strtobin.split():
    el1=elem.encode('ascii')
    print (el1)
    #print(elem)
    pos = pos + sh
    fdata.seek(pos,1)
    fdata.write(el1)

解决方法

您可以执行以下操作:

from pathlib import Path

PAD = b'\x00\00'

with Path("in.txt").open("r") as infile,Path("out.bin").open("wb") as  out_file:
    for line in infile:
        for char in line:
            out_file.write(PAD)
            out_file.write(char.encode())
     out_file.write(PAD)

只需在每个字符和文件的结尾处写上PAD

如果"in.txt"仅由字符串"python"组成,该字符串应或多或少地再现您期望的输出。

,

也许我误解了您要执行的操作,但是您的代码对于要执行的操作却显得非常复杂。

为什么不只是

for ch in text:
     <Not sure if you want to write 2 0's or skip two bytes>
     Write ch as a byte

跳过两个字节为file.seek(2,1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。