C++ 如何 sprintf 一个无符号字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2050404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sprintf an unsigned char?
提问by Christoferw
This doesn't work:
这不起作用:
unsigned char foo;
foo = 0x123;
sprintf("the unsigned value is:%c",foo);
I get this error:
我收到此错误:
cannot convert parameter 2 from 'unsigned char' to 'char'
无法将参数 2 从“无符号字符”转换为“字符”
回答by MAK
Before you go off looking at unsigned chars causing the problem, take a closer look at this line:
在您开始查看导致问题的无符号字符之前,请仔细查看这一行:
sprintf("the unsigned value is:%c",foo);
The first argument of sprintf is always the string to which the value will be printed. That line should look something like:
sprintf 的第一个参数始终是值将打印到的字符串。该行应如下所示:
sprintf(str, "the unsigned value is:%c",foo);
Unless you meant printf instead of sprintf.
除非你的意思是 printf 而不是 sprintf。
After fixing that, you can use %u in your format string to print out the value of an unsigned type.
修复后,您可以在格式字符串中使用 %u 打印出无符号类型的值。
回答by Ariel
Use printf()
formta string's %u
:
使用printf()
formta 字符串的%u
:
printf("%u", 'c');
回答by Christoferw
EDIT
编辑
snprintf
is a little more safer. It's up to the developer to ensure the right buffer size is used.
snprintf
更安全一点。确保使用正确的缓冲区大小取决于开发人员。
Try this :
尝试这个 :
char p[255]; // example
unsigned char *foo;
...
foo[0] = 0x123;
...
snprintf(p, sizeof(p), " 0x%X ", (unsigned char)foo[0]);
回答by eduffy
I think your confused with the way sprintf
works. The first parameter is a string buffer, the second is a formatting string, and then the variables you want to output.
我认为您对工作方式感到困惑sprintf
。第一个参数是字符串缓冲区,第二个参数是格式化字符串,然后是要输出的变量。
回答by R Samuel Klatchko
You should not use sprintf as it can easily cause a buffer overflow.
您不应该使用 sprintf,因为它很容易导致缓冲区溢出。
You should prefer snprintf (or _snprintf when programming with the Microsoft standard C library). If you have allocated the buffer on the stack in the local function, you can do:
在使用 Microsoft 标准 C 库进行编程时,您应该更喜欢 snprintf(或 _snprintf)。如果您在本地函数中在堆栈上分配了缓冲区,则可以执行以下操作:
char buffer[SIZE];
snprintf(buffer, sizeof(buffer), "...fmt string...", parameters);
The data may get truncated but that is definitely preferable to overflowing the buffer.
数据可能会被截断,但这绝对比溢出缓冲区更可取。