将std :: string从UTF8,UTF16,ISO88591转换为十六进制

时间:2019-10-28 01:58:11

标签: encoding utf-8 c++14 utf-16 iso-8859-1

我尝试将std :: string从UTF8,...编码为十六进制。我现在不能做的是,如果输入字符串包含来自代码页标识符(windows-1258)包含越南语字符的特殊字符,我将无法获得输入字符串每个字符的十进制值来进行转换。

首先,我将获取十进制值,然后将其转换为Binary,然后转换为Hexadecimal。 s是我的输入字符串。 s =“Ồ”。

void StringUtils::strToBinary(wstring s, string* result)
{
    int n = s.length();
    for (int i = 0; i < n; i++)
    {
        wchar_t c = s[i];
        long val = long(c);
        std::string bin = "";
        while (val > 0)
        {
            (val % 2) ? bin.push_back('1') :
                bin.push_back('0');
            val /= 2;
        }
        reverse(bin.begin(), bin.end());
        result->append(convertBinToHex(bin));
    }
}

std::string StringUtils::convertBinToHex(std::string temp) {
    long long binaryValue = atoll(temp.c_str());
    long long dec_value = 0;
    int base = 1;
    int i = 0;


    while (binaryValue) {
        long long last_digit = binaryValue % 10;

        binaryValue = binaryValue / 10;

        dec_value += last_digit * base;

        base = base * 2;

    }
    char hexaDeciNum[10];
    while (dec_value != 0)
    {
        int temp = 0;
        temp = dec_value % 16;
        if (temp < 10)
        {
            hexaDeciNum[i] = temp + 48;
            i++;
        }
        else
        {
            hexaDeciNum[i] = temp + 55;
            i++;
        }
        dec_value = dec_value / 16;
    }
    std::string str;
    for (int j = i - 1; j >= 0; j--) {
        str = str + hexaDeciNum[j];
    }
    return str;
}

如果我的输入仅包含“Ồ”,这就是我的预期输出

UTF8 : E1BB92
UTF16 : FEFF 1ED2
UTF16BE : 1ED2
UTF16LE : D21E

这是我在Java中的操作方式

    Charset charset = Charset.forName(Enum.valueOf(Encoding.class, encodingType).toString());
    ByteBuffer buffer = charset.newEncoder().encode(CharBuffer.wrap(inputString.toCharArray()));
    byte[] bytes = new byte[buffer.limit()];
    buffer.get(bytes, 0, buffer.limit());
    result = new ByteField(bytes);
    return result;
            } 

0 个答案:

没有答案