Base conversion (CJam)
An easy way to encode ASCII strings that do not start with a null byte is to convert from base 128 to integer, then to base 256:
128b256b:c e# Prints encoded string.
128b256b:c`"256b128b:c" e# Prints encoded string with decoder.
This uses 7 bits to encode each ASCII character.
If the original string consists only of, e.g., lowercase letters, and does no start with an a, we can start by mapping "a...z"
to [0 ... 25]
, then proceed as above:
'afm26b256b:c e# Prints encoded string.
'afm26b256b:c`"256b26b'af+" e# Prints encoded string with decoder.
Finally, if the original string has only a few unique characters (common in ASCII art), it is usually better to specify the alphabet explicitly.
For example:
" +-/\|"f#6b256b:c e# Prints encoded string.
" +-/\|"f#6b256b:c`"256b6b"" +-/\|"`"f=" e# Prints encoded string with decoder.
As a rule of thumb, you want the first character of the original string to be the second character of the alphabet, the next distinct character of the original string to be the first character of the alphabet, the next distinct character of the original string to be the third character of the alphabet, the next distinct character of the original string to be the fourth character of the alphabet, etc.
The encoder of last example works as follows:
" +-/\|"f# e# Replace each character by its index in that string.
6b256b e# Convert from base 6 (length of the alphabet) to base 256.
:c e# Cast each digit to character.
The decoder of last example works as follows:
256b6b e# Convert from base 256 to base 6.
" +-/\|"f= e# Replace each digit by the corresponding character of the alphabet.