C++ 十六进制字符串和短整型相互转换

一、十六进制字符串转短整型,包含大小端

short getShortFromHexStr(string hexStr, bool isBigEdian)
{
    if (hexStr.length() != 4) {
        return 0;
    }
    string bigEdianStr = hexStr;
    // 先将小端字符串转大端字符串
    if (!isBigEdian) {
        bigEdianStr = "";
        // 按字节掉转顺序,例如 0A00-->000A
        for (int i = hexStr.length() - 2; i >= 0; i -= 2) {
            bigEdianStr += hexStr.substr(i, 2);
        }
    }
    return std::stoi(bigEdianStr, 0, 16);
}

二、短整型 转十六进制字符串,包含大小端

string getHexStrFromShort(short data, bool isBigEdian)
{
    int from = data;
    char to[4];
    itoa(from, to, 16);
    string tmp = to;

    string prefix0 = "";
    // 补0
    if (tmp.length() < 4) {
        for (unsigned int i = 0; i < 4 - tmp.length(); i++) {
            prefix0 += "0";
        }
    }
    tmp = prefix0 + tmp;
    string result = tmp;
    if (!isBigEdian) {
        result = "";
        // 按字节掉转顺序,例如 0A00-->000A
        for (int i = tmp.length() - 2; i >= 0; i -= 2) {
            result += tmp.substr(i, 2);
        }
    }
    return result;
}

你可能感兴趣的:(C++,c++)