How to sprintf an unsigned char?


Question

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'

1
14
1/12/2010 4:23:27 PM

Accepted Answer

Use printf() formta string's %u:

printf("%u", 'c');
18
4/9/2018 9:13:30 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon