[英]wchar_t to std::string in hex format
I'm trying to convert a wchar_t
to a hexadecimal and then convert it to std::string
.我正在尝试将wchar_t
转换为十六进制,然后将其转换为std::string
。
Here is my code:这是我的代码:
#ifdef _DEBUG
std::clog << wchar << std::endl;
#endif
wchar_t wideChar = printf("0x%x", wchar);
#ifdef _DEBUG
std::clog << wideChar << std::endl;
#endif
std::string str = "";
str.assign(wideChar, 4);
#ifdef _DEBUG
std::clog << str << std::endl;
#endif
wchar is a variable of type wchar_t and it has a dynamic value. wchar 是 wchar_t 类型的变量,它具有动态值。 I'm using the value 69 in this example which is the equivalent of the E key.在此示例中,我使用的值 69 相当于 E 键。
First I'm converting the wchar to another wchar_t and this wideChar holds the hexadecimal value.首先,我将 wchar 转换为另一个 wchar_t,这个 wideChar 保存十六进制值。 This works like expected except it has one more character I don't need/want.这就像预期的那样工作,除了它还有一个我不需要/想要的字符。
At the end I'm trying to convert the wide char to string and this fails horribly.最后,我试图将宽字符转换为字符串,这非常失败。 The idea behind this is I only need the first 4 letters of the hexadecimal number (like 0x45 not 0x454).这背后的想法是我只需要十六进制数字的前 4 个字母(比如 0x45 而不是 0x454)。
Example Output:示例输出:
69
0x454
♦♦♦♦
The biggest problem I have is that the string only has this weird symbols in it.我遇到的最大问题是字符串中只有这个奇怪的符号。 I want to convert the wchar to string exactly how it is but I want to remove the last character.我想将 wchar 完全转换为字符串,但我想删除最后一个字符。
The desired output should be:所需的输出应该是:
69
0x454
0x45
Can someone tell me what my code is doing wrong and how I can do it right.有人可以告诉我我的代码做错了什么以及如何正确地做。 Thanks in advance.提前致谢。
This:这个:
str.assign(wideChar, 4);
uses this overload:使用这个重载:
constexpr basic_string& assign( size_type count, CharT ch );
Since you assigned the number of characters transmitted to stdout
in由于您分配了传输到stdout
的字符数
wchar_t wideChar = printf("0x%x", wchar);
to wideChar
, then wideChar
is 4
( 0x45
makes it 4 characters).到wideChar
,然后wideChar
是4
( 0x45
使它成为 4 个字符)。
So, you assign four char(4)
s to the string, making it "\004\004\004\004"
.因此,您将四个char(4)
分配给字符串,使其成为"\004\004\004\004"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.