How to sprintf an unsigned char?

81,703

Solution 1

Use printf() formta string's %u:

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

Solution 2

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.

Solution 3

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.

Solution 4

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.

Share:
81,703
Christoferw
Author by

Christoferw

Full Stack Developer | Software Strategy Consultant

Updated on April 09, 2020

Comments

  • Christoferw
    Christoferw about 4 years

    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'

  • Ariel
    Ariel over 14 years
    No - notice I'm calling printf, not sprintf, just to give an example of the "%u" you need to get the decimal value of the char.
  • Dolphin
    Dolphin over 14 years
    also, 0x123 is too big to fit in a unsigned char. You probaly want foo = 123 (ascii '{' ).
  • MSalters
    MSalters over 14 years
    @Dolphin: probably. But it will fit on those systems where UCHAR_BIT > 8, e.g. 16 bit DSP's.