Shell/C++字符串转16进制

xingyun86 2022-8-18 559

Shell

ascii字符串转换成16进制

#!/bin/bash
asciiStr="ABCDEFG"

for c in $(echo $asciiStr|sed 's/./& /g')
do
   hexArr=$hexArr" "$(printf "%X" "'$c")
done
 
echo "hexArr:"$hexArr

16进制转换成ascii字符串

hexStr="41 42 43 44 45 46 47"

hexArray=$(echo $(echo $hexStr | sed 's/ //g')|sed 's/../& /g')
for hexC in $hexArray
do
    obtainAsciiStr=$obtainAsciiStr$(printf "\x$hexC")
done
echo "$obtainAsciiStr"

C++

ascii字符串转换成16进制

string asciiToHex(const string& asciiStr)
{
    string ret;
    static const char *hex = "0123456789ABCDEF";
    for (auto c:asciiStr)
    {
        ret.push_back(hex[(c >> 4) & 0xf]);
        ret.push_back(hex[c & 0xf]);
    }
    return ret;
}

16进制转换成ascii字符串

string hexToAscii(const char* hexArr, const int length)
{
    int readI = 0;
    int inputI = 0;
    std::string resultValue(length / 2);
    while (hexArr[2 * readI] != '\0' && hexArr[2 * readI + 1] != '\0') {
        char c = hexArr[2 * readI];
        char hex = hexArr[2 * readI];
 
        if(c <= '9') {
            hex = (c - '0') << 4;
        } else if(c <= 'F') {
            hex = (c - 'A' + 10) << 4;
        } else {
            hex = (c - 'a' + 10) << 4;
        }
        c = hexArr[2 * readI + 1];
        if(c <= '9') {
            hex |= c - '0';
        } else if(c <= 'F') {
            hex |= c - 'A' + 10;
        } else {
            hex |= c - 'a' + 10;
        }
        if (hex >= '!' && hex <= '~') {
            resultValue[inputI] = hex;
            inputI++;
        }
        readI++;
    }
    resultValue[inputI] = '\0';
    return resultValue;
}

附上一张ASCII表



×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回