How to sprintf an unsigned char?

Christoferw picture Christoferw · Jan 12, 2010 · Viewed 79.7k times · Source

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'

Answer

MAK picture MAK · Jan 12, 2010

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.