Advertisement
KKosty4ka

text (un)quacker

Mar 14th, 2023 (edited)
727
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. text to quacks encoder/decoder
  3. version 1
  4. by KKosty4ka
  5.  
  6. use the encodeText and decodeText functions
  7. (or the encodeBytes and decodeBytes if you are crazy enough to encode byte arrays with this)
  8. */
  9.  
  10. function encodePunctuation(b5, b6, b7)
  11. {
  12.     var output = "";
  13.    
  14.     if (b5 && b6) output = "?";
  15.     else if (b5 && !b6) output = "!";
  16.     else if (!b5 && b6) output = "?!";
  17.    
  18.     if (b7) output = output.padEnd(output.length === 2 ? 4 : 3, ".");
  19.     return output;
  20. }
  21.  
  22. function encodeWord(b0, b1, b2, b3, b4)
  23. {
  24.     var output = "";
  25.    
  26.     output += b0 ? "Q" : "q";
  27.     output += b1 ? "U" : "u";
  28.     output += b2 ? "A" : "a";
  29.     output += b3 ? "C" : "c";
  30.     output += b4 ? "K" : "k";
  31.    
  32.     return output;
  33. }
  34.  
  35. function encodeByte(byte)
  36. {
  37.     return encodeWord(
  38.         byte & 0b00000001,
  39.         byte & 0b00000010,
  40.         byte & 0b00000100,
  41.         byte & 0b00001000,
  42.         byte & 0b00010000
  43.     ) + encodePunctuation(
  44.         byte & 0b00100000,
  45.         byte & 0b01000000,
  46.         byte & 0b10000000
  47.     );
  48. }
  49.  
  50. function encodeBytes(bytes)
  51. {
  52.     return [...bytes].map(encodeByte).join(" ");
  53. }
  54.  
  55. function encodeText(text)
  56. {
  57.     return encodeBytes(new TextEncoder().encode(text));
  58. }
  59.  
  60.  
  61. function decodePunctuation(text)
  62. {
  63.     var b5 = 0;
  64.     var b6 = 0;
  65.     var b7 = +text.endsWith(".");
  66.    
  67.     if (text.startsWith("?!")) b6 = 1;
  68.     else if (text.startsWith("!")) b5 = 1;
  69.     else if (text.startsWith("?")) b5 = b6 = 1;
  70.    
  71.     return [b5, b6, b7];
  72. }
  73.  
  74. function decodeWord(text)
  75. {
  76.     var output = [];
  77.    
  78.     for (var i = 0; i < 5; i++)
  79.     {
  80.         output.push(+(text[i] === text[i].toUpperCase()));
  81.     }
  82.    
  83.     return output;
  84. }
  85.  
  86. function decodeByte(text)
  87. {
  88.     var bits = decodeWord(text).concat(decodePunctuation(text.substring(5)));
  89.     var output = 0;
  90.  
  91.     for (var i = 0; i < 8; i++)
  92.     {
  93.         output += bits[i] * (1 << i);
  94.     }
  95.    
  96.     return output;
  97. }
  98.  
  99. function decodeBytes(text)
  100. {
  101.     return new Uint8Array(text.split(" ").map(decodeByte));
  102. }
  103.  
  104. function decodeText(text)
  105. {
  106.     return new TextDecoder().decode(decodeBytes(text));
  107. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement