在 C++ 中定义 UTF-16BE 字符串

发布于 2024-12-27 12:44:58 字数 222 浏览 4 评论 0原文

我需要定义如下所示的 unicode 字符串:

const char SOME_STRING[] = { 0, 5, 0, 'M', 0, 'y', 0, 'S', 0, 't', 0, 'r' };

这是 UTF-16BE 字符串,前面带有包含长度的大端短字节,它在 java 中使用,这就是我需要它的用途。有没有比单独输入每个字符更好/更干净的方法来声明它?

I need to define unicode string that would look like so:

const char SOME_STRING[] = { 0, 5, 0, 'M', 0, 'y', 0, 'S', 0, 't', 0, 'r' };

This is UTF-16BE string prepended with big endian short containing length, it's used in java and that's what I need it for. Is there better/cleaner way to declare it than typing every character separately?

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

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

发布评论

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

评论(2

喜爱纠缠 2025-01-03 12:44:58

您可以使用 wchar_t 代替,按需转换为字节,例如:

const wchar_t some_string[] = L"\x05MyStr";

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i <= some_string[0]; i++)
        printf("%d %d ", some_string[i] >> 8, some_string[i] & 0xFF);

    return 0;
}

You could use wchar_t instead, converting to bytes on demand, for example:

const wchar_t some_string[] = L"\x05MyStr";

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i <= some_string[0]; i++)
        printf("%d %d ", some_string[i] >> 8, some_string[i] & 0xFF);

    return 0;
}
卷耳 2025-01-03 12:44:58

C 和 C++ 没有定义它们所运行的平台的字节序性质如何工作。因此,语言本身无法将 16 位值序列声明为“大端”。

您所要做的就是获取平台本机字节序中的字符串。如果平台的字节序不是大字节序,则进行字节交换。您可以将字节交换版本存储在 std::vector 或类似文件中。

C and C++ do not define how the endian nature of the platform they are running on works. Therefore, there is no way within the language themselves to declare a sequence of 16-bit values to be "big endian".

What you have to do is get the string in the platform native endian. Then do byte swapping if the endian-ness of the platform is not big endian. You can store the byte-swapped version in a std::vector or some such.

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