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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With