gpt4 book ai didi

c++ - 如何在 C++ 中的 cout/cerr 上打印 USB 字符串描述符?

转载 作者:行者123 更新时间:2023-11-28 05:28:14 24 4
gpt4 key购买 nike

我在 uint8_t 数组中有一个 USB 字符串描述符。例如:

0000:12 03 34 00 45 00 36 00 31 00 42 00 43 00 30 00 ..4.E.6.1.B.C.0.
0010:30 00 0.

(前两个字节是长度和描述符类型;其余字节是uint16_t字符。)

我想尽可能少地在终端上打印它,最好不要在所有其他打印上搞砸(就像 cout << "Hello, world" << endl; 一样)

特别是,我想做:

cout << "Serial number is: " << some_cast_or_constructor( buf + 2, len - 2 ) << endl;

对于上面的字符串描述符,在终端上获取以下内容:

Serial number is: 4E61BC00

这可能吗,还是我必须深入研究 Unicode 奥秘?

[编辑添加:]

Per @PaulMcKenzie,我试过这个程序:

#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <locale>

int
main( int argc, char **argv )
{
char buf[] = { 34, 00, 45, 00, 36, 00, 31, 00, 42, 00, 43, 00, 30, 00, 30, 00 };

std::wcout << "Hello" << std::wstring( (const wchar_t *)buf, sizeof(buf) ) << std::endl;

return 0;
}

输出:

user:/tmp$ g++ foo.cc
user:/tmp$ ./a.out
Hello??????????
user:/tmp$

最佳答案

在您的源代码中,我检测到两个错误:1- 在您的 USB 原始数据(顶部)中,值是十六进制的,而在您的 buf[] 中,值是十进制的。应该写成:

    char    buf[] = { 0x34, 0x00, 0x45, 0x00, 0x36, 0x00, 0x31, 0x00, 0x42,
0x00, 0x43, 0x00, 0x30, 0x00, 0x30, 0x00 };

2- 在您的打印消息中,长度等于 sizeof(buf) 但它是“char”(1 字节)而不是“wchar_t”(2 字节)。应该写成:

std::wcout << "Hello" << std::wstring( (const wchar_t *)buf, (sizeof(buf) >> 1) ) << std::endl;

而且,这段代码在 Windows PC 上给出了预期的结果......在您的计算机上管理“wchar_t”之前,请确保没有大/小端转换。

Could you check the sizeof(wchar_t) under Linux ? This post 'Difference and conversions between wchar_t for Linux and for Windows' supposes that wchar_t is a 32bits value.

关于c++ - 如何在 C++ 中的 cout/cerr 上打印 USB 字符串描述符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40078007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com