Introduction
The RFC 4648 (The Base16, Base32, and Base64 Data Encodings) defines different
methods to encode binary data. Every Unix like system has the tool base64
installed to encode and decode data using the base64 alphabet. This alphabet
includes the characters A-Z, a-z, 0-9, +, / for the data and = for padding. The
base16 encoding scheme, better known as hex encoding, uses the alphabet 0-9 and
A-F. This encoding is case-insensitive. The GNU coreutils do not include a
base16 tool. I searched for a hex encoding and decoding tool with the same
functionality as base64
without success. That’s why I wrote a script so I can
use it to hex encode and decode binary data. Basically, it’s a wrapper around
some Perl code.
Base16 Theory
The RFC 4648 (The Base16, Base32, and Base64 Data Encodings) tells us, that 4 bits can be represented by a character of the alphabeth of 0-9 and A-F. This is due to the fact, that 2^4 is 16 and the alpabeth has 16 different characters. Therefore, a byte uses two characters of this alpabeth.
This is an extract of the RFC:
Script
The script base16
can be found on GitHub: https://github.com/emanuelduss/Scripts/blob/master/base16.
On Arch Linux, you can install base16 from the Arch User Repository (AUR):
Usage
The script base16
offers the same options and functionallty as the base64
tool. The usage can be displayed with the -h
option:
The data are encoded as described for the base16 alphabet in RFC 4648.
When decoding, the input may contain newlines in addition to the bytes of
the formal base64 alphabet. Use --ignore-garbage
to attempt to recover
from any other non-alphabet bytes in the encoded stream.
Examples
For example, you can encode some data. When no file is provided, the data is read from standard input:
If you don’t like the linebreaks, use the -w 0
options do disable it:
This can then be decoded again using base16
:
Update 2020
I learned that the tool basenc
from the GNU coreutils
is able to convert hex/base16:
$ echo -en "Hello World\nThis is a test with a newline" | basenc --base16 -w 0
48656C6C6F20576F726C640A546869732069732061207465737420776974682061206E65776C696E65
$ basenc --decode --base16 --ignore-garbage <<< 48656C6C6F20576F726C640A546869732069732061207465737420776974682061206E65776C696E65
Hello World
This is a test with a newline
This is much easier, because it does not require any additional scripts. The base16
script is therefore not necessary anymore ;-).
If you use it a lot, you can add the following alias into your .bashrc
to save some keystrokes:
alias base16="basenc --base16"
References
- RFC 4648: The Base16, Base32, and Base64 Data Encodings: https://tools.ietf.org/html/rfc4648
- base16 in the Arch Linux User Repository (AUR): https://aur.archlinux.org/packages/base16/
- GNU Coreutils Tools: http://git.savannah.gnu.org/cgit/coreutils.git/tree/src