diff --git a/ascii.hpp b/ascii.hpp index 50b75a57..7f3fdb29 100644 --- a/ascii.hpp +++ b/ascii.hpp @@ -11,11 +11,11 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2016 Danny Robson + * Copyright 2016-2018 Danny Robson */ -#ifndef __CRUFT_UTIL_ASCII_HPP -#define __CRUFT_UTIL_ASCII_HPP +#ifndef CRUFT_UTIL_ASCII_HPP +#define CRUFT_UTIL_ASCII_HPP #include "annotation.hpp" @@ -125,4 +125,40 @@ namespace util::ascii { } } + +/////////////////////////////////////////////////////////////////////////////// +#include "debug.hpp" +#include + +/// convert an ascii string of hex digits into a vector of uint8 +std::vector +inline +operator"" _hex2u8 (const char *str, size_t len) +{ + CHECK_MOD (len, 2); + std::vector res (len/2); + + for (size_t i = 0; i < len; i += 2) + res[i/2] = util::ascii::from_hex (str[i]) << 4 | util::ascii::from_hex (str[i+1]); + return res; +}; + + +/////////////////////////////////////////////////////////////////////////////// +template +constexpr auto +operator"" _hex2array (void) +{ + static_assert (sizeof ...(StrV) % 2 == 0); + + std::array res {}; + constexpr CharT literal[] = { StrV... }; + + for (size_t i = 0; i < res.size (); ++i) + res[i] = util::ascii::from_hex (literal[i*2+0]) << 4 | + util::ascii::from_hex (literal[i*2+1]); + + return res; +} + #endif diff --git a/test/ascii.cpp b/test/ascii.cpp index 6c17d64c..8a91a8a2 100644 --- a/test/ascii.cpp +++ b/test/ascii.cpp @@ -75,5 +75,8 @@ main (int, char**) ); } + tap.expect_eq ("6a"_hex2u8, std::vector({0x6a}), "hex2u8, 1 byte"); + tap.expect_eq ("a6"_hex2array, std::array ({0xa6}), "hex2array, 1 byte"); + return tap.status (); }