============================= 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. .. sourcecode:: cpp :linenos: :dedent: :caption: Using hex encoding #include using namespace liberate::string; std::string input{"Hello, world!"}; // Hexadecimal encoding doubles the number of bytes required. std::vector hex; hex.resize(input.size() * 2); hexencode(&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. .. sourcecode:: cpp :linenos: :dedent: :caption: Using hex encoding (simpler) auto hex = hexencode(input.c_str(), input.size()); // => std::string Once we have a hex encoded string, we can also decode it. .. sourcecode:: cpp :linenos: :dedent: :caption: Using hex decoding auto decoded = hexdecode(hex.c_str(), hex.size()); assert(decoded == input); .. seealso:: - :cpp:func:`liberate::string::hexencode` - :cpp:func:`liberate::string::hexdecode` 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. .. _hexdump(1): https://man7.org/linux/man-pages/man1/hexdump.1.html .. sourcecode:: cpp :linenos: :dedent: :caption: Using hex decoding canonical_hexump hd; std::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 :cpp:struct:`liberate::string::hexdump` struct with specific template parameter values. You can roll your own preferred display instead. .. seealso:: - :cpp:struct:`liberate::string::hexdump` - :cpp:type:`liberate::string::canonical_hexdump` - :cpp:type:`liberate::string::wide_hexdump`