Skip to content

Instantly share code, notes, and snippets.

@JFreegman
Last active October 1, 2020 05:21
Show Gist options
  • Save JFreegman/7112702069e82a37038a819d0d1a1512 to your computer and use it in GitHub Desktop.
Save JFreegman/7112702069e82a37038a819d0d1a1512 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from sys import argv
"""
Converts a string representation of a sorted array of integers `s` into a bitfield.
e.g. indicesToBin("1 2 4 9 10 13 15 17 18 20 21 25 26 28 29 33 34 36 37 38 39")
-> "01101000011001010110110001101100011011110"
@return a string representation of the resulting bitfield.
"""
def indicesToBin(s):
L = [int(ch) for ch in s.split(' ')]
size = L[-1] + (8 - (L[-1] % 8))
bitfield = [0 for i in range(size + 1)]
for n in L:
bitfield[n] = 1
return ''.join(str(b) for b in bitfield)
"""
Converts string `s` into a sorted array of integers where each value n corresponds to the n-th
index in a bitfield comprising the binary formatted string in which the bit is turned on.
e.g. strToArrayIndices("hello")
-> "1 2 4 9 10 13 15 17 18 20 21 25 26 28 29 33 34 36 37 38 39"
@return a string representation of the resulting array.
"""
def strToArrayIndices(s):
L = [i for (i, bit) in enumerate(''.join([format(ord(ch), '08b') for ch in s])) if bit == '1']
return ' '.join(str(x) for x in L)
def main(cmd, s):
if cmd == 'to':
print(strToArrayIndices(s))
elif cmd == 'from':
print(indicesToBin(s))
if __name__ == '__main__':
if len(argv) != 3:
print("Usage: ./translate [to|from] [string]")
exit(1)
cmd = argv[1].lower()
s = argv[2]
if cmd not in ["to", "from"]:
print("Usage: ./translate [to|from] [string]")
exit(1)
main(cmd, s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment