views:

1471

answers:

5

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  A: 

Try this :

char p[255]; // example
unsigned char *foo;
...
foo[0] = 0x123;
...
sprintf(p, " 0x%X ", (unsigned char)foo[0]);
0A0D
it's just an example.. you need to sprintf into an unsigned char of something. p is a string buffer
0A0D
then i get these error: subscript requires array or pointer type
Christoferw
we need to see more code.
0A0D
ok, so it has to be printf instead of sprintf....
Christoferw
+2  A: 

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

Ariel
this works, i have to use printf instead of sprintf
Christoferw
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
+2  A: 

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
+14  A: 

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
also, 0x123 is too big to fit in a unsigned char. You probaly want foo = 123 (ascii '{' ).
Dolphin
@Dolphin: probably. But it will fit on those systems where `UCHAR_BIT` > 8, e.g. 16 bit DSP's.
MSalters
A: 

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