How to turn a hex string into an unsigned char array?

后端 未结 7 1260
春和景丽
春和景丽 2020-11-27 06:05

For example, I have a cstring \"E8 48 D8 FF FF 8B 0D\" (including spaces) which needs to be converted into the equivalent unsigned char array {0xE8,0x48,0

7条回答
  •  暖寄归人
    2020-11-27 06:50

    This answers the original question, which asked for a C++ solution.

    You can use an istringstream with the hex manipulator:

    std::string hex_chars("E8 48 D8 FF FF 8B 0D");
    
    std::istringstream hex_chars_stream(hex_chars);
    std::vector bytes;
    
    unsigned int c;
    while (hex_chars_stream >> std::hex >> c)
    {
        bytes.push_back(c);
    }
    

    Note that c must be an int (or long, or some other integer type), not a char; if it is a char (or unsigned char), the wrong >> overload will be called and individual characters will be extracted from the string, not hexadecimal integer strings.

    Additional error checking to ensure that the extracted value fits within a char would be a good idea.

提交回复
热议问题