table_enc_12bit.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/python3
  2. def tr(x):
  3. """Translate a 6-bit value to the Base64 alphabet."""
  4. s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
  5. + 'abcdefghijklmnopqrstuvwxyz' \
  6. + '0123456789' \
  7. + '+/'
  8. return ord(s[x])
  9. def table(fn):
  10. """Generate a 12-bit lookup table."""
  11. ret = []
  12. for n in range(0, 2**12):
  13. pre = "\n\t" if n % 8 == 0 else " "
  14. pre = "\t" if n == 0 else pre
  15. ret.append("{}0x{:04X}U,".format(pre, fn(n)))
  16. return "".join(ret)
  17. def table_be():
  18. """Generate a 12-bit big-endian lookup table."""
  19. return table(lambda n: (tr(n & 0x3F) << 0) | (tr(n >> 6) << 8))
  20. def table_le():
  21. """Generate a 12-bit little-endian lookup table."""
  22. return table(lambda n: (tr(n >> 6) << 0) | (tr(n & 0x3F) << 8))
  23. def main():
  24. """Entry point."""
  25. lines = [
  26. "#include <stdint.h>",
  27. "",
  28. "const uint16_t base64_table_enc_12bit[] = {",
  29. "#if BASE64_LITTLE_ENDIAN",
  30. table_le(),
  31. "#else",
  32. table_be(),
  33. "#endif",
  34. "};"
  35. ]
  36. for line in lines:
  37. print(line)
  38. if __name__ == "__main__":
  39. main()