简体   繁体   English

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

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

I just started working with C++, after a few weeks I figured out that C++ doesn't support a method or library to convert a string to Hexa value.我刚开始使用 C++,几周后我发现 C++ 不支持将字符串转换为 Hexa 值的方法或库。 Currently, I'm working on a method that will return the hexadecimal value of an input string encode in UTF16.目前,我正在研究一种方法,该方法将返回以 UTF16 编码的输入字符串的十六进制值。 For an easier understanding of what I'm trying to do, I will show what I have done in Java.为了更容易理解我想要做什么,我将展示我在 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();
    }

What I have try to do in C++:我在 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));
    }
}

My main function:我的主function:

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

Although I get the expected values, but is there any other way to do it?虽然我得到了预期值,但还有其他方法吗? Any help would be really appreciated.任何帮助将非常感激。 Thanks in advance.提前致谢。

This is really ugly and can be simplified but it's at least an improvement.这真的很难看,可以简化,但至少是一种改进。 If I wasn't on mobile I would give something better.如果我不在手机上,我会提供更好的东西。

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

That's for a byte array, doesn't really matter but if you want to iterate as wchar_t then it's even easier.那是一个字节数组,并不重要,但如果你想迭代为 wchar_t 那就更容易了。

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

You can use std::stringstream to write a number in hex format, then output that stream to a std::string.您可以使用std::stringstream以十六进制格式write数字,然后将 output 即 stream 写入 std::string。 Here's a working example:这是一个工作示例:

#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;
}

Or, to convert a character string into a string of hex numbers:或者,将字符串转换为十六进制数字字符串:

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

For more information on (string)stream formatting options, see here .有关(字符串)流格式选项的更多信息,请参见此处

Feel free to ask for further clarification and/or explanation.随时要求进一步澄清和/或解释。

Just use boost:只需使用提升:

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

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

Explanation:解释:

  • u on front of the string means create UTF-16 string literal .字符串前面的u表示创建 UTF-16字符串文字
  • s on the end of string literal means convert literal to respective std::basic_string , in this case it is std::u16string , this is done by using namespace std::literals;字符串文字末尾的s表示将文字转换为相应的std::basic_string ,在这种情况下是std::u16string ,这是通过using namespace std::literals; see doc .文档
  • boost::algorithm::hex_lower . boost::algorithm::hex_lower

Here is live demo .这是现场演示

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

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