Below is a complete, self-contained “toy” text-encoding system called ZigZag-8 (ZZ8 for short).
It is NOT cryptographically secure; it is only meant to demonstrate how to design, encode, decode, and ship a tiny custom codec with a minimal GUI.
────────────────────────────────────────
- The ZZ8 Encoding Rules
────────────────────────────────────────
• Every Unicode code-point is split into 8-bit chunks (little-endian).
• Each chunk is bit-reversed (so 0b11010010 → 0b01001011).
• The chunks are written zig-zag:
– 1st chunk forward, 2nd backward, 3rd forward, 4th backward …
• A single 0xFF byte marks end-of-stream.
• ASCII letters (0x41–0x5A, 0x61–0x7A) are left untouched for readability.
Example
“Hi” → [0x48, 0x69] → already ASCII → literal bytes 0x48 0x69 0xFF.
“©” (U+00A9) → 0xA9 → bit-reverse → 0x95 → zig-zag forward → 0x95 0xFF.
────────────────────────────────────────
2. File Layout
────────────────────────────────────────
zz8.py # codec + CLI
zz8_gui.py # tiny Tkinter reader / encoder / decoder
README_ZZ8.md # this explanation (optional)
Run either file directly; they are independent.
────────────────────────────────────────
3. The Codec (zz8.py)
────────────────────────────────────────
#!/usr/bin/env python3
"""
zz8.py – ZigZag-8 text codec
Usage:
python zz8.py encode "Some text" # → hex
python zz8.py decode A9FF # → text
python zz8.py file plain.txt out.zz8 # file mode
"""
import sys, re, pathlib
ASCII_RANGE = range(0x41, 0x5A + 1), range(0x61, 0x7A + 1)
def _is_ascii_letter(cp: int) -> bool:
return any(cp in r for r in ASCII_RANGE)
def _bit_reverse(b: int) -> int:
return int(f"{b:08b}"[::-1], 2)
def encode(text: str) -> bytes:
out = bytearray()
for ch in text:
cp = ord(ch)
if _is_ascii_letter(cp):
out.append(cp)
continue
# Split into 8-bit little-endian chunks
chunks = []
while cp:
chunks.append(cp & 0xFF)
cp >>= 8
if not chunks:
chunks = [0]
# Zig-zag + bit-reverse
for idx, chunk in enumerate(chunks):
rev = _bit_reverse(chunk)
if idx & 1: # even indices are forward, odd backward
out.insert(len(out) - idx, rev)
else:
out.append(rev)
out.append(0xFF)
return bytes(out)
def decode(data: bytes) -> str:
if data and data[-1] == 0xFF:
data = data[:-1]
chars, idx = [], 0
while idx < len(data):
b = data[idx]
if _is_ascii_letter(b):
chars.append(chr(b))
idx += 1
continue
# Collect zig-zag chunks
chunks, rev = [], False
while idx < len(data) and not _is_ascii_letter(data[idx]):
if rev:
chunks.insert(0, _bit_reverse(data[idx]))
else:
chunks.append(_bit_reverse(data[idx]))
rev = not rev
idx += 1
# Re-assemble code-point
cp = 0
for c in reversed(chunks):
cp = (cp << 8) | c
chars.append(chr(cp))
return ''.join(chars)
# ------------------------------------------------------------------
# CLI
# ------------------------------------------------------------------
def _hex(b: bytes) -> str: return b.hex()
def _unhex(s: str) -> bytes: return bytes.fromhex(re.sub(r'\s+', '', s))
if __name__ == "__main__":
if len(sys.argv) < 2:
print("See source for usage."); sys.exit(1)
cmd = sys.argv[1]
if cmd == "encode":
txt = sys.argv[2] if len(sys.argv) > 2 else sys.stdin.read()
print(_hex(encode(txt)))
elif cmd == "decode":
blob = _unhex(sys.argv[2]) if len(sys.argv) > 2 else _unhex(sys.stdin.read())
print(decode(blob))
elif cmd == "file":
src, dst = pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])
if src.suffix.lower() == ".zz8":
dst.write_text(decode(src.read_bytes()), encoding="utf-8")
else:
dst.write_bytes(encode(src.read_text(encoding="utf-8")))
else:
print("Unknown command"); sys.exit(1)
────────────────────────────────────────
4. The GUI (zz8_gui.py)
────────────────────────────────────────
#!/usr/bin/env python3
"""
zz8_gui.py – minimal reader / encoder / decoder
Requires: Python 3.7+, tkinter (ships with CPython on Windows & most *nix)
"""
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import zz8 # reuse codec above
class ZZ8Gui(tk.Tk):
def __init__(self):
super().__init__()
self.title("ZigZag-8 Reader / Encoder / Decoder")
self.geometry("700x500")
self._build_ui()
def _build_ui(self):
frm = tk.Frame(self)
frm.pack(fill="both", expand=True, padx=10, pady=10)
tk.Label(frm, text="Plain text (UTF-8)").grid(row=0, column=0, sticky="w")
self.txt_plain = scrolledtext.ScrolledText(frm, height=8)
self.txt_plain.grid(row=1, column=0, sticky="nsew")
tk.Label(frm, text="ZZ8 hex").grid(row=2, column=0, sticky="w")
self.txt_hex = scrolledtext.ScrolledText(frm, height=8)
self.txt_hex.grid(row=3, column=0, sticky="nsew")
btn_bar = tk.Frame(frm)
btn_bar.grid(row=4, column=0, pady=5)
tk.Button(btn_bar, text="Encode →", command=self.encode).pack(side="left", padx=5)
tk.Button(btn_bar, text="← Decode", command=self.decode).pack(side="left", padx=5)
tk.Button(btn_bar, text="Load .txt / .zz8", command=self.load_file).pack(side="left", padx=5)
tk.Button(btn_bar, text="Save .txt / .zz8", command=self.save_file).pack(side="left", padx=5)
frm.columnconfigure(0, weight=1)
frm.rowconfigure(1, weight=1)
frm.rowconfigure(3, weight=1)
# ----------------------------------------------------------
def encode(self):
try:
txt = self.txt_plain.get("1.0", "end-1c")
self.txt_hex.delete("1.0", "end")
self.txt_hex.insert("1.0", zz8.encode(txt).hex())
except Exception as e:
messagebox.showerror("Encode error", str(e))
def decode(self):
try:
hexstr = self.txt_hex.get("1.0", "end-1c").strip()
data = bytes.fromhex(hexstr)
self.txt_plain.delete("1.0", "end")
self.txt_plain.insert("1.0", zz8.decode(data))
except Exception as e:
messagebox.showerror("Decode error", str(e))
# ----------------------------------------------------------
def load_file(self):
path = filedialog.askopenfilename(filetypes=[("All", "*.*")])
if not path:
return
try:
if path.lower().endswith(".zz8"):
data = pathlib.Path(path).read_bytes()
self.txt_hex.delete("1.0", "end")
self.txt_hex.insert("1.0", data.hex())
self.txt_plain.delete("1.0", "end")
self.txt_plain.insert("1.0", zz8.decode(data))
else:
txt = pathlib.Path(path).read_text(encoding="utf-8")
self.txt_plain.delete("1.0", "end")
self.txt_plain.insert("1.0", txt)
self.encode()
except Exception as e:
messagebox.showerror("Load error", str(e))
def save_file(self):
if self.txt_plain.get("1.0", "end-1c").strip():
default = "out.zz8"
data = zz8.encode(self.txt_plain.get("1.0", "end-1c"))
mode = "wb"
else:
default = "out.txt"
data = zz8.decode(bytes.fromhex(self.txt_hex.get("1.0", "end-1c")))
mode = "w"
path = filedialog.asksaveasfilename(initialfile=default)
if not path:
return
try:
if "b" in mode:
pathlib.Path(path).write_bytes(data)
else:
pathlib.Path(path).write_text(data, encoding="utf-8")
messagebox.showinfo("Saved", f"Wrote {path}")
except Exception as e:
messagebox.showerror("Save error", str(e))
if __name__ == "__main__":
import pathlib # late import for GUI
ZZ8Gui().mainloop()
────────────────────────────────────────
5. Quick Test
────────────────────────────────────────
pythonzz8.pyencode"Helloc◯"48656c python zz8.py decode 48656c6c6f2095FF
Hello ©
Launch the GUI:
$ python zz8_gui.py
────────────────────────────────────────
6. Extending / Hacking
────────────────────────────────────────
• Replace the ASCII passthrough with Base-64 or a custom symbol table.
• Swap bit-reversal for a tiny 8-bit S-box.
• Add a checksum or CRC before the 0xFF sentinel.
• Embed the codec in a codecs module hook so open("file.zz8", encoding="zz8") works.
Have fun encoding!