16

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'

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
Christoferw
  • 741
  • 3
  • 7
  • 20
  • Are you sure the error isn't "cannot convert parameter 2 from 'unsigned char' to 'char *'? – Richard Pennington Jan 12 '10 at 16:27
  • 5
    You are missing a parameter to sprintf() The first parameter is the output buffer. The second is the format string. All remaining depend on the format string. If you just want to print to the std out use printf() (note no 's' at the beginning). – Martin York Jan 12 '10 at 16:30
  • I recommend you check to see if it `isalnum(..)` versus actual hex value instead of arbitrarily printing the character value. Not all have visible hex values such as 0x01. –  Jan 12 '10 at 16:31

5 Answers5

35

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.

MAK
  • 26,140
  • 11
  • 55
  • 86
21

Use printf() formta string's %u:

printf("%u", 'c');
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Ariel
  • 5,752
  • 5
  • 49
  • 59
  • 3
    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. – Ariel Jan 12 '10 at 16:28
6

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]);
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.

eduffy
  • 39,140
  • 13
  • 95
  • 92
1

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.

R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187