所以為了好玩,我很好奇我是否能在編譯時(shí)完成這種轉(zhuǎn)換。它沒(méi)有太多的錯(cuò)誤檢查,并且是在VS 2015中完成的,它還不支持C+14 Conexpr函數(shù)(這就是HexCharToInt的樣子)。它采用c-字符串?dāng)?shù)組,將一對(duì)字符轉(zhuǎn)換為單個(gè)字節(jié),并將這些字節(jié)展開(kāi)為一個(gè)統(tǒng)一的初始化列表,用于初始化作為模板參數(shù)提供的T類(lèi)型。T可以替換為像std:Array這樣的東西來(lái)自動(dòng)返回?cái)?shù)組。
#include <cstdint>#include <initializer_list>#include <stdexcept>#include <utility>/* Quick and dirty conversion from a single character to its hex equivelent */constexpr std::uint8_t HexCharToInt(char Input){
return
((Input >= 'a') && (Input <= 'f'))
? (Input - 87)
: ((Input >= 'A') && (Input <= 'F'))
? (Input - 55)
: ((Input >= '0') && (Input <= '9'))
? (Input - 48)
: throw std::exception{};}/* Position the characters into the appropriate nibble */constexpr std::uint8_t HexChar(char High, char Low){
return (HexCharToInt(High) << 4) | (HexCharToInt(Low));}/* Adapter that performs sets of 2 characters into a single byte and combine the results into a uniform initialization list used to initialize T */template <typename T, std::size_t Length, std::size_t ... Index>constexpr T HexString(const char (&Input)[Length], const std::index_sequence<Index...>&){
return T{HexChar(Input[(Index * 2)], Input[((Index * 2) + 1)])...};}/* Entry function */template <typename T, std::size_t Length>constexpr T HexString(const char (&Input)[Length]){
return HexString<T>(Input, std::make_index_sequence<(Length / 2)>{});}constexpr auto Y = KS::Utility::HexString<std::array<std::uint8_t, 3>>("ABCDEF");