Converting a hex string to a byte array

后端 未结 19 2133
时光取名叫无心
时光取名叫无心 2020-11-22 12:10

What is the best way to convert a variable length hex string e.g. \"01A1\" to a byte array containing that data.

i.e converting this:

st         


        
19条回答
  •  春和景丽
    2020-11-22 13:02

    So for fun, I was curious if I could do this kind of conversion at compile-time. It doesn't have a lot of error checking and was done in VS2015, which doesn't support C++14 constexpr functions yet (thus how HexCharToInt looks). It takes a c-string array, converts pairs of characters into a single byte and expands those bytes into a uniform initialization list used to initialize the T type provided as a template parameter. T could be replaced with something like std::array to automatically return an array.

    #include 
    #include 
    #include 
    #include 
    
    /* 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 
    constexpr T HexString(const char (&Input)[Length], const std::index_sequence&)
    {
        return T{HexChar(Input[(Index * 2)], Input[((Index * 2) + 1)])...};
    }
    
    /* Entry function */
    template 
    constexpr T HexString(const char (&Input)[Length])
    {
        return HexString(Input, std::make_index_sequence<(Length / 2)>{});
    }
    
    constexpr auto Y = KS::Utility::HexString>("ABCDEF");
    

提交回复
热议问题