Last active
February 20, 2022 11:54
-
-
Save 4hg/bc2992204032f2143f50bc1d3fe2917f to your computer and use it in GitHub Desktop.
Base32 Encoder and Decoder in J
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
NB. ENCODER | |
NB. information about algorithm came from https://herongyang.com/Encoding/Base32-Encoding-Algorithm.html | |
NB. RFC 4648 character set | |
cs =: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' | |
NB. interval array | |
ia =: {{0 = 5 | i. # y}} | |
NB. padded length value | |
pl =: {{5 * >. 5 %~ # y}} | |
pad =: (pl $!.(0{a.) ])&.> | |
NB. split stream, pad, and unbox | |
ss =: > @ pad @ <;.1~ ia | |
NB. bit groups | |
bgs =: [: (8,5)&($,)"2 (8#2) #: a. i. ] | |
NB. override count | |
oc =: [: {&(0 6 4 3 1 0) # - ([: -&5 pl) | |
map =: [: {&cs #. | |
NB. override | |
o =: (-@[ }. ,@]) , #&'='@[ | |
NB. encode | |
e =: oc o map@bgs@ss | |
NB. DECODER | |
NB. dyadic: count x in y | |
c =: +/@:= | |
NB. dyadic: remove all x from y | |
sc =: -@:c }. ] | |
NB. convert to bgs and add null rows | |
conv =: {{ (#: cs i. '=' sc y) , (5,~ '=' c y) $ 0 }} | |
NB. calculate new shape to go from shape (n 5) to (m 8) | |
ns =: {{8 ,~ 5 * 8 %~ # y}} | |
NB. reshape | |
rs =: ns ($,) ] | |
NB. decode | |
d =: {{ u: 0 sc #. rs conv y }} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment