Skip to content

Instantly share code, notes, and snippets.

@dbanetto
Created May 18, 2014 02:05
Show Gist options
  • Save dbanetto/2b04a2539a915ab2a4f3 to your computer and use it in GitHub Desktop.
Save dbanetto/2b04a2539a915ab2a4f3 to your computer and use it in GitHub Desktop.
Solves : encoding/decoding two binary strings together into one binary string
#!/usr/bin/python3
def main():
print (decode(encode("101" , "1011")))
print (decode(encode("1101" , "1011")))
print (decode(encode("10010101" , "1011")))
# Reads read the source C
# Decodes by getting the 1st 2 bits from the string
# 1st bit (from left) is the End of String bit
# 2nd bit is the value of the bit
def decode(C):
A = ""
B = ""
eosA = False #End of String A
eosB = False #End of String B
abit = True #Flag for what bit to read
while C != "":
bit = C[:2]
C = C[2:]
#Check what bit we are looking at
if (abit):
#Do not change if the other string has ended
if not eosB:
abit = not abit
if not eosA:
if (bit[0] == '1'):
eosA = True
A = A + bit[1]
else:
#Do not change if the other string has ended
if not eosA:
abit = not abit
# If you have not reached the end of B string
if not eosB:
if (bit[0] == '1'):
eosB = True
B = B + bit[1]
return [A ,B ]
# Outputs a Binary string of 2*(A + B ) length
# Each bit is interlaced from the string A then B
# Each bit from the source strings are converted
def encode(A ,B):
C = ""
eof = False
while not eof:
#Deal with A
if A != "":
#Substring and remove the 1st char
ab = A[:1] #a's bit
A = A[1:]
else:
ab = '1'
#Check if this was the last bit
if A != "":
ab = '0' + ab
else:
if ab != "":
ab = '1' + ab
#Deal with B
if B != "":
bb = B[:1] #a's bit
B = B[1:]
else:
bb = ''
#Check if this was the last bit
if B != "":
bb = '0' + bb
else:
if bb != "":
bb = '1' + bb
if B == "" and A == "":
eof = True
C = C + ab + bb
return C
if(__name__ == '__main__'):
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment