开发者

How to sprintf an unsigned char?

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'


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(str, "the unsigned value is:%c",foo);

Unless you meant printf instead of sprintf.

After fixing that, you can use %u in your format string to print out the value of an unsigned type.


Use printf() formta string's %u:

printf("%u", 'c');


EDIT

snprintf is a little more safer. It's up to the developer to ensure the right buffer size is used.

Try this :

char p[255]; // example
unsigned char *foo;
...
foo[0] = 0x123;
...
snprintf(p, sizeof(p), " 0x%X ", (unsigned char)foo[0]);


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.


You should not use sprintf as it can easily cause a buffer overflow.

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:

char buffer[SIZE];
snprintf(buffer, sizeof(buffer), "...fmt string...", parameters);

The data may get truncated but that is definitely preferable to overflowing the buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜