|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Manchester Codec - Manchester content encoding. |
| 3 | +
|
| 4 | +This codec: |
| 5 | +- en/decodes strings from str to str |
| 6 | +- en/decodes strings from bytes to bytes |
| 7 | +- decodes file content to str (read) |
| 8 | +- encodes file content from str to bytes (write) |
| 9 | +""" |
| 10 | +from ..__common__ import * |
| 11 | + |
| 12 | + |
| 13 | +__examples1__ = {'enc(manchester)': {'This is a test!': "fei\x95i\x96jZYUi\x96jZYUiVYUjeifjZjeYV"}} |
| 14 | +__examples2__ = { |
| 15 | + 'enc(manchester-inverted|ethernet|ieee802.4)': { |
| 16 | + 'This is a test!': "\x99\x9a\x96j\x96i\x95\xa5\xa6\xaa\x96i\x95\xa5\xa6\xaa\x96\xa9\xa6\xaa\x95\x9a\x96\x99" |
| 17 | + "\x95\xa5\x95\x9a\xa6\xa9", |
| 18 | + }, |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +def manchester_encode(clock): |
| 23 | + def encode(text, errors="strict"): |
| 24 | + r = "" |
| 25 | + for c in text: |
| 26 | + bin_c = bin(ord(c))[2:].zfill(8) |
| 27 | + for i in range(0, 8, 4): |
| 28 | + r += chr(int("".join(2*bit for bit in bin_c[i:i+4]), 2) ^ clock) |
| 29 | + return r, len(b(text)) |
| 30 | + return encode |
| 31 | + |
| 32 | + |
| 33 | +def manchester_decode(clock): |
| 34 | + def decode(text, errors="strict"): |
| 35 | + r, bits = "", "" |
| 36 | + for c in text: |
| 37 | + bin_c = bin(ord(c) ^ clock)[2:].zfill(8) |
| 38 | + bits += "".join(bin_c[i] for i in range(0, len(bin_c), 2)) |
| 39 | + if len(bits) == 8: |
| 40 | + r += chr(int(bits, 2)) |
| 41 | + bits = "" |
| 42 | + return r, len(b(text)) |
| 43 | + return decode |
| 44 | + |
| 45 | + |
| 46 | +add("manchester", manchester_encode(0x55), manchester_decode(0x55), examples=__examples1__) |
| 47 | +add("manchester-inverted", manchester_encode(0xaa), manchester_decode(0xaa), examples=__examples2__, |
| 48 | + pattern=r"^(?:manchester-inverted|ethernet|ieee802\.4)$") |
| 49 | + |
0 commit comments