0

I am trying to create a bin file with script below which should write bytes from user input and with offset bytes in between every character. But there is a problem where it writes sequentially all bytes and does not separate after each byte with added offset byte defined with '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

How I want it to be

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

Here is the code for the program

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)

2 Answers 2

1

you could do something like this:

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)

just write PAD after every character and a the very end of the file.

if "in.txt" just consists of the string "python" that should more or less reproduce your desired output.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps I'm misunderstanding what you're trying to do, but your code looks awfully complicated for what it's trying to do.

Why not just

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

Skipping two bytes is file.seek(2, 1)

1 Comment

I wanted to skip two bytes after each byte (for a character), so I can later read those bin files with seek and specific offset values known only to the creator of this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.