Duplicating Contents Of Bin File X Times And Keeping In Order

- 1 answer

I am attempting to take a binary file and duplicate the contents in order:

Say the file contains 101010101010101. I want to duplicate each bit by x (say 3 for this example) and make a copy of the file so that the copied file with the duplicates will read as 111000111000111000111000111000111000111000111.

I then want to be able to reverse this as well.

The issue I am having is how to read each element, and then write that element x times in a new file. I am able to copy the file, however unsure how to read each element and then duplicate it



I don't know if you already tried something or if you are having any trouble with your solution.

But suppose you already read the file you need and already assigned the value from the file to a variable, you could do:

# Define the bit content
bit = '101010101010101'
# Number that will duplicate each bit
times = 3
# New bit content
new_bit = ''

# Loop through each char in bit
for b in bit:
    new_bit += b*times

# Reverse the new bit
reverse_new_bit = new_bit[::-1]

# Save output to a new file
file = open(r'file.txt', 'w')

You can also change this to a function and read each file calling the function.

If you print(new_bit):


If you check if the new_bit is different than the example you shared by print('111000111000111000111000111000111000111000111' != new_bit):


If you print(reverse_new_bit):