How-To work with hex encoding
Sometimes it is usefult to represent values in hexadecimal encoding, and/or decode hexadecimal values back into binary. This library contains some functions that help here.
Hex encode and decode
Start by hex encoding some input string.
1#include <liberate/string/hexencode.h>
2
3using namespace liberate::string;
4
5std::string input{"Hello, world!"};
6
7// Hexadecimal encoding doubles the number of bytes required.
8std::vector<char> hex;
9hex.resize(input.size() * 2);
10
11hexencode(&hex[0], hex.size(), input.c_str(), input.size());
Note
A lot of C++ developers are not aware that this is legal use of vector, which guarantees that its elements are contiguous in memory. Don’t assume this to work with other containers, however.
Of course, we can also make this a tad more convenient.
1auto hex = hexencode(input.c_str(), input.size());
2// => std::string
Once we have a hex encoded string, we can also decode it.
1auto decoded = hexdecode(hex.c_str(), hex.size());
2assert(decoded == input);
Creating hex dumps of some memory buffer
When you work with a lot of binary data, hex encoding a string is not always the easiest way to understand what you are dealing with. On the command line, the hexdump(1) tool may help you. But what to do in code?
Fear not, we can do much the same.
1canonical_hexump hd;
2
3std::cerr << hd(buf, bufsize) << std::endl;
The canonical_hexdump
formats the contents of the specified buffer much like
using hexdump -C would on the CLI. We can also use wide_hexdump
for an
alternative view.
However, both are just uses of the liberate::string::hexdump
struct with specific template parameter values. You can roll your own preferred
display instead.