24. String to binary conversion

The operation requested here is the opposite of the one implemented in the previous problem. This time, however, we could write a function and not a function template. The input is an std::string_view, which is a lightweight wrapper for a sequence of characters. The output is a vector of 8-bit unsigned integers. The following hexstr_to_bytes function transforms every two text characters into an unsigned char value ("A0" becomes 0xA0), puts them into an std::vector, and returns the vector:

unsigned char hexchar_to_int(char const ch){   if (ch >= '0' && ch <= '9') return ch - '0';   if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;   if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; throw std::invalid_argument("Invalid ...

Get The Modern C++ Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.