Christoferw
Christoferw

Reputation: 760

How to sprintf an unsigned char?

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'

Upvotes: 17

Views: 91610

Answers (5)

Ariel
Ariel

Reputation: 5830

Use printf() formta string's %u:

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

Upvotes: 21

user195488
user195488

Reputation:

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

Upvotes: 6

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76601

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.

Upvotes: 1

MAK
MAK

Reputation: 26586

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.

Upvotes: 36

eduffy
eduffy

Reputation: 40242

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.

Upvotes: 3

Related Questions