uint8_t与16进制std::string的相互转换

时间:2025-02-09 20:28:33
#include <>
#include <sstream>
#include <>
#include <string>
#include <algorithm>

// 将uint8_t转换为16进制的std::string
std::string encodeToHexStr(uint8_t uint8Var, bool upperCase) {
    int intVar = (int)uint8Var;
    std::stringstream ss;
    ss << std::hex << intVar;
    std::string hexStrVar = ();
    if (upperCase) {
        std::transform((), (), (), ::toupper);
    } else {
        std::transform((), (), (), ::tolower);
    }
    return hexStrVar;
}

// 将16进制的std::string转换为uint8_t
bool decodeFromHexStr(std::string hexStr, uint8_t& ucValue) {
    const char* bufStr = hexStr.c_str();
    ucValue = 0;

    char buf[3], tmpChar;
    memset((void*)buf, 0, 3);
    size_t sizeStr = strlen(bufStr);
    if (sizeStr < 1) {
        return false;
    }

    if (sizeStr == 1) {
        buf[0] = '0';
        buf[1] = bufStr[0];
    } else {
        memcpy((void*)buf, (void*)bufStr, 2);
    }

    for (int i = 0; i < 2; i++) {
        tmpChar = buf[i];
        ucValue = ucValue * 16;
        if (tmpChar >= '0' && tmpChar <= '9') {
            ucValue = ucValue + (uint8_t)(tmpChar - '0');
        } else if (tmpChar >= 'a' && tmpChar <= 'f') {
            ucValue = ucValue + (uint8_t)(tmpChar - 'a' + 10);
        } else if (tmpChar >= 'A' && tmpChar <= 'F') {
            ucValue = ucValue + (uint8_t)(tmpChar - 'A' + 10);
        } else {
            return false;
        }
    }
    return true;
}