Sometimes you need to encode bytes into a text.
Most popular encodings are hex, where each byte is represented by 2 characters and base64 where each 3 bytes are encoded as 4 characters.
We can encode a []byte into a string and decode from string into []byte.
https://codeeval.dev/gist/f055282edd12292e0f5aaa3fa1537e80
fmt.SprintfWe can encode to string using fmt.Sprintf and %x directive. Similarly, we can decode using fmt.Sscanf and %x.
Directive %x supports integers in addtion to []byte.
https://codeeval.dev/gist/61fae43f06ff7450316ec59759c42834
For encoding and decoding larger values in streaming mode, we can encode to a io.Writer and decode from io.Reader.
https://codeeval.dev/gist/0e7af9c5080dc1b63751c56d629176ae
We can encode a []byte into a string and decode from string into []byte.
https://codeeval.dev/gist/520d1b4a31345752abdce2e552695aea
Original base64 encoding unfortunately might produce characters that are not valid in urls.
Given that urls are important those days we have a variant of base64 encoding that doesn’t have that flaw:
https://codeeval.dev/gist/e4c2199e28c07ca8b06f8222c52da408