0
votes

I have unsigned char variable which stores ASCII code of some symbol (e.g., '1'). I want to print the symbol. Am I using the correct format specifier? Is this well defined? or should I cast it to int inside sprintf?

unsigned char unsignedCharVar = 49;
sprintf(dest,"%c", unsignedCharVar); // should print '1'
2
But regarding your problem, I sense a bit of the XY problem. Why do you want to do this? Is there a reason you use unsigned char to store, essentially, characters? And if you want to print the characters as a character then you need to cast the variable to be correct, which might cause UB if char is signed and the value is over 127. - Some programmer dude
@JoachimPileborg: Yes, let's assume I need to use unsigned char array to store character so how do I print it? Where do I do the cast? - anon
sprintf(dest,"%c", unsignedCharVar); // should print '1' here sprintf does not print anything. try printf("%s",dest); after your sprintf. - Jayesh Bhoi
@Jayesh: I know that I am asking about format specifier inside sprintf. - anon

2 Answers

1
votes

u specifies unsigned for all types so try %uc.

0
votes

You do not need to cast to char, since (non-extended) ASCII has codes 0-127, which means the representation is the same in both unsigned and signed char. You just have to make sure that your unsigned char contains a valid value.