Created
October 20, 2015 14:44
-
-
Save moreati/aa326a21a5a06613c517 to your computer and use it in GitHub Desktop.
A way to visualize byte strings, by (ab)using the 256 braille characters in Unicode 3.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
UNICODE_BRAILLE_BASE = 0x2800 | |
def int2bits(v): | |
""" | |
>>> int2bits(25) | |
[0, 0, 0, 1, 1, 0, 0, 1] | |
""" | |
assert 0 <= v <= 255 | |
return [(v >> i) & 1 for i in range(7, -1, -1)] | |
def bits2int(v): | |
""" | |
>>> bits2int([0,0,0,0, 1,1,1,1]) | |
15 | |
""" | |
assert len(v) == 8 | |
return sum((bit << (7-i) for i, bit in enumerate(v))) | |
# https://en.wikipedia.org/wiki/Braille_Patterns | |
bitpos2braillepos = { | |
4:0, 0:3, | |
5:1, 1:4, | |
6:2, 2:5, | |
7:6, 3:7, | |
} | |
braillepos2bitpos = { | |
0:4, 3:0, | |
1:5, 4:1, | |
2:6, 5:2, | |
6:7, 7:3, | |
} | |
def byte2dots(byte): | |
""" | |
>>> [byte2dots(i) for i in (0xff, 0xf0, 0x31, 0x00)] | |
['⣿', '⡇', '⠋', '⠀'] | |
""" | |
bits = int2bits(byte) | |
bits.reverse() | |
dots = [bits[braillepos2bitpos[i]] for i in range(8)] | |
dots.reverse() | |
braillechar = chr(UNICODE_BRAILLE_BASE + bits2int(dots)) | |
return braillechar | |
def bytes2dots(s): | |
""" | |
>>> single_bits = b'\x01\x02\x04\x08\x10\x20\x40\x80' | |
>>> complements = ((~ byte) & 255 for byte in single_bits) | |
>>> bytes2dots(single_bits) | |
'⠈ ⠐ ⠠ ⢀ ⠁ ⠂ ⠄ ⡀' | |
>>> bytes2dots(complements) | |
'⣷ ⣯ ⣟ ⡿ ⣾ ⣽ ⣻ ⢿' | |
""" | |
return ' '.join(byte2dots(byte) for byte in s) | |
if __name__ == '__main__': | |
print(bytes2dots(b'\xff\xf3\xf1\xf0\x0f\x1f\x3f\xff')) | |
print(bytes2dots(b'\x01\x02\x04\x08\x10\x20\x40\x80')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment