如何使用C ++获得输入字符串的十六进制值?

问题描述 投票:0回答:2

我刚开始使用C ++,几周后我发现C ++不支持将字符串转换为Hexa值的方法或库。目前,我正在研究一种方法,该方法将返回以UTF16编码的输入字符串的十六进制值。为了更轻松地了解我要做什么,我将展示我在Java中所做的事情。

Charset charset = Charset.forName("UTF16");
String str = "Ồ";
try {
        ByteBuffer buffer = charset.newEncoder().encode(CharBuffer.wrap(str.toCharArray()));
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes, 0, buffer.limit());
        System.out.println("Hex value : " + bytes); // 1ED2
    } 
catch (CharacterCodingException ex) {
        ex.printStackTrace();
    }

我在C ++中尝试做的事情:

std::string 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;
}

void 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));
    }
}

我的主要功能:

 int main()
    {
        std::string result;
        std::wstring input = L"Ồ";
        strToBinary(input, &result);
        cout << result << endl;// 1ED2
        return 0;
    }

虽然我得到了期望值,但是还有其他方法吗?任何帮助将非常感激。预先感谢。

c++ utf-16
2个回答
0
投票
auto buf = reinterpret_cast<uint8_t*>(input.data()); auto sz = (input.size() * sizeof(wchar_t)); for (size_t i = 0; i < input.size() * sizeof(wchar_t); ++i) { char p[8] = {0}; sprintf(p, "%02X", buf[i]); output += p; }

这是一个字节数组,并不重要,但是如果要迭代为wchar_t,则更加简单。

for (const auto& i : input)
{
    char p[8] = {0};
    sprintf(p, "%04X", i);
    output += p;
}

0
投票
#include <iostream> #include <sstream> #include <string> int main() { int i = 0x03AD; std::stringstream ss; s << std::hex << i; // The std::hex tells the stream to use HEX format std::string ans; ss >> ans; // Put the formatted output into our 'answer' string std::cout << ans << std::endl; // For demo, write the string to the console return 0; }

随时要求进一步的澄清和/或解释。

© www.soinside.com 2019 - 2024. All rights reserved.