Tam Nguyen
Tam Nguyen

Reputation: 1165

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. Currently, I'm working on a method that will return the hexadecimal value of an input string encode in UTF16. For an easier understanding of what I'm trying to do, I will show what I have done in 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++:

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:

 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.

Upvotes: 4

Views: 1755

Answers (3)

Adrian Mole
Adrian Mole

Reputation: 51825

You can use std::stringstream to write a number in hex format, then output that stream to a 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.

Upvotes: 3

Marek R
Marek R

Reputation: 37667

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.
  • 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; see doc.
  • boost::algorithm::hex_lower.

Here is live demo.

Upvotes: 3

Pickle Rick
Pickle Rick

Reputation: 808

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.

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

Upvotes: 3

Related Questions