Chr*_*erw 14 c++ printf unsigned-char
这不起作用:
unsigned char foo;
foo = 0x123;
sprintf("the unsigned value is:%c",foo);
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
无法将参数2从'unsigned char'转换为'char'
MAK*_*MAK 35
在您查看导致问题的未签名字符之前,请仔细查看此行:
sprintf("the unsigned value is:%c",foo);
Run Code Online (Sandbox Code Playgroud)
sprintf的第一个参数始终是要打印值的字符串.该行应该类似于:
sprintf(str, "the unsigned value is:%c",foo);
Run Code Online (Sandbox Code Playgroud)
除非你的意思是printf而不是sprintf.
修复之后,您可以在格式字符串中使用%u来打印出无符号类型的值.
Ari*_*iel 18
使用printf()formta字符串%u:
printf("%u", 'c');
Run Code Online (Sandbox Code Playgroud)
小智 6
编辑
snprintf更安全一点.由开发人员来确保使用正确的缓冲区大小.
试试这个 :
char p[255]; // example
unsigned char *foo;
...
foo[0] = 0x123;
...
snprintf(p, sizeof(p), " 0x%X ", (unsigned char)foo[0]);
Run Code Online (Sandbox Code Playgroud)