如何在二进制文件中使用偏移量从输入写入字节?

2024-05-19 12:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个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)

Tags: keytextinpostxtfor字节shift
2条回答

也许我误解了你的意图,但是你的代码看起来非常复杂

为什么不

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)

你可以这样做:

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"组成,该字符串应该或多或少地再现所需的输出

相关问题 更多 >