繁体   English   中英

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

[英]How can I get the hex value of an input string using C++?

我刚开始使用 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));
    }
}

我的主function:

 int main()
    {
        std::string result;
        std::wstring input = L"Ồ";
        strToBinary(input, &result);
        cout << result << endl;// 1ED2
        return 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;
}

您可以使用std::stringstream以十六进制格式write数字,然后将 output 即 stream 写入 std::string。 这是一个工作示例:

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>

int main()
{
    int i = 0x03AD;
    std::stringstream ss;
    // The following line sets up ss to use FIXED 8-digit output with leading zeros...
    ss << std::setw(8) << std::setfill('0'); // Comment out or adjust as required
    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;
}

或者,将字符串转换为十六进制数字字符串:

int main()
{
    std::string ins;
    std::cout << "Enter String: ";
    std::cin >> ins;

    std::stringstream ss;
    ss << std::setfill('0') << std::hex; // Set up format
    for (auto c : ins) ss << std::setw(4) << int(c); // Need to set width for each value!

    std::string ans;
    ss >> ans;
    std::cout << ans << std::endl;
    return 0;
}

有关(字符串)流格式选项的更多信息,请参见此处

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

只需使用提升:

using namespace std::literals;
auto u16stringg = u"你好,世界"s;

std::string result;
boost::algorithm::hex_lower(u16stringg.begin(), u16stringg.end(), std::back_inserter(result));

解释:

  • 字符串前面的u表示创建 UTF-16字符串文字
  • 字符串文字末尾的s表示将文字转换为相应的std::basic_string ,在这种情况下是std::u16string ,这是通过using namespace std::literals; 文档
  • boost::algorithm::hex_lower

这是现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM