wchar_t to std :: string以十六进制格式

发布于 2025-02-09 11:05:43 字数 854 浏览 2 评论 0原文

我正在尝试将WCHAR_T转换为十六进制,然后将其转换为std :: String

这是我的代码:

#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是类型WCHAR_T的变量,它具有动态值。我在此示例中使用值69,这等同于e密钥。

首先,我将WCHAR转换为另一个WCHAR_T,并且此Widechar具有十六进制值。这就像预期的那样起作用,除了它还有一个我不需要/想要的角色。

最后,我试图将宽阔的炭转换为弦乐,这将发生可怕的失败。背后的想法是我只需要十六进制数字的前4个字母(例如0x45而不是0x454)。

示例输出:

69
0x454
♦♦♦♦

我遇到的最大问题是字符串中只有此怪异的符号。我想将WCHAR转换为符号的方式,但我想删除最后一个字符。

所需的输出应该是:

69
0x454
0x45

有人可以告诉我我的代码做错了什么以及如何正确地做到这一点。提前致谢。

I'm trying to convert a wchar_t to a hexadecimal and then convert it to 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. I'm using the value 69 in this example which is the equivalent of the E key.

First I'm converting the wchar to another wchar_t and this wideChar holds the hexadecimal value. 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).

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖公主 2025-02-16 11:05:43

以下:

str.assign(wideChar, 4);

使用此重载:

constexpr basic_string& assign( size_type count, CharT ch );

由于您分配了传输到stdout的字符数,然后

wchar_t wideChar = printf("0x%x", wchar);

widechar,然后widechar4代码>(0x45使其成为4个字符)。

因此,您将四个char(4) s分配给字符串,使其“ \ 004 \ 004 \ 004 \ 004 \ 004”

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

wchar_t wideChar = printf("0x%x", wchar);

to wideChar, then wideChar is 4 (0x45 makes it 4 characters).

So, you assign four char(4)s to the string, making it "\004\004\004\004".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文