Created
August 14, 2023 20:55
-
-
Save Romern/c9c048637a4b7a0ce25d2eb5e71ea997 to your computer and use it in GitHub Desktop.
base64 encoder in postscript
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
/base64EncodingTable [ | |
(A) (B) (C) (D) (E) (F) (G) (H) (I) (J) | |
(K) (L) (M) (N) (O) (P) (Q) (R) (S) (T) | |
(U) (V) (W) (X) (Y) (Z) (a) (b) (c) (d) | |
(e) (f) (g) (h) (i) (j) (k) (l) (m) (n) | |
(o) (p) (q) (r) (s) (t) (u) (v) (w) (x) | |
(y) (z) (0) (1) (2) (3) (4) (5) (6) (7) | |
(8) (9) (+) (/) | |
] def | |
% takes 3 bytes and returns their 4 base64 encoded values | |
/threeBytesToFourChars { | |
/b3 exch def | |
/b2 exch def | |
/b1 exch def | |
% first 6 of b1 | |
/c1 b1 2#11111100 and -2 bitshift def | |
% last 2 of b1, first 4 of b2 | |
/c2 | |
b1 2#00000011 and 4 bitshift % last 2 of b1 | |
b2 2#11110000 and -4 bitshift % first 4 of b2 | |
xor | |
def | |
% last 4 of b2, first 2 of b3 | |
/c3 | |
b2 2#00001111 and 2 bitshift % last 4 of b2 | |
b3 2#11000000 and -6 bitshift % first 2 of b3 | |
xor | |
def | |
% last 6 of b3 | |
/c4 b3 2#00111111 and def | |
c4 c3 c2 c1 | |
} def | |
% (a) (b) -> (ab) | |
% https://stackoverflow.com/questions/12378904/postscript-concatenate-two-strings | |
/concat { exch dup length | |
2 index length add string | |
dup dup 4 2 roll copy length | |
4 -1 roll putinterval | |
} bind def | |
% TODO: Fix for non mod 3 strings | |
/base64Encode { | |
/inputString exch def | |
/outputString () def | |
0 3 inputString length 1 sub { | |
/i exch def | |
/curChars [ | |
inputString i 3 getinterval | |
{} forall | |
threeBytesToFourChars | |
] def | |
/curOut () def | |
curChars { | |
/curChar exch def | |
/curOut base64EncodingTable curChar get curOut concat def | |
} forall | |
/outputString outputString curOut concat def | |
} for | |
outputString | |
} def |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment