Reputation: 159
I have a binary String. I add 1 at every 7-th position in that string. Using the following code.
binary='1010010110000110100101100001'
# insert 1 after every 7 bit.
new_binary='1'.join(binary[i:i+7] for i in range(0, len(binary), 7))
print(new_binary)
my output String:
1010010111000011101001011100001
Now I want to remove those extra 1 from the output string and get back the Original String. For that I try to identify the position of those 1 I tried the following approach:
binary='1010010111000011101001011100001'
# remove 1 after every 7 bit.
for i in range(0, len(binary), 7):
if((i+7) <len(binary)):
print("current position = ",i+7, "Value of the position: ", binary[i+7])
print("\n")
and my current output is:
('current position = ', 7, 'Value of the position: ', '1')
('current position = ', 14, 'Value of the position: ', '1')
('current position = ', 21, 'Value of the position: ', '1')
('current position = ', 28, 'Value of the position: ', '0')
now from the output, you can see that the first output is OK. But for the 2nd output, 'current position = ' should be 15 instead of 14. and the 3rd output should be 23 instead of 21. And there should be no 4th output. Any help regarding this. please.
N.B: I'm trying to do this for a larger bit string.
Upvotes: 1
Views: 243
Reputation: 140307
the opposite transform needs you to have a step of 7+1 to remove the extra 1
added every 7 characters.
You can print the correct position by printing the 7th character every 8 characters, like this:
for i in range(0, len(new_binary), 8):
if((i+8) <len(new_binary)):
print("current position = ",i+7, "Value of the position: ", new_binary[i+7])
print("\n")
Now, how to retrieve the original string?
This can be done with the "inverse" comprehension you used to create the first string.
binary='1010010110000110100101100001'
# insert 1 after every 7 bit.
new_binary='1'.join(binary[i:i+7] for i in range(0, len(binary), 7))
print(new_binary)
old_binary = "".join(new_binary[i:i+7] for i in range(0, len(new_binary), 8))
print(old_binary==binary)
prints True
:)
Upvotes: 1