Reputation: 13614
I need to convert integer value to char value in C. What is the proper way to do it ?
Regards...
Upvotes: 1
Views: 10745
Reputation: 106068
They're implicitly convertible...
int x = 65;
char c = x; // 'A'
putchar(x);
printf("%c", x);
char asciiz[] = { 65, 32, 66, 32, 67, 0 };
You can do it explicitly with e.g. (char)65
, especially useful in C++ where overloading and templates make writing code that behaves different depending on the type common.
If you actually mean to get a (possibly multiple-)character representation of a number, then you can use printf("%d", x) to print it to standard output, or:
char buffer[16]; // biggest int is 4 billion so ~10 chars, round up for safety
sprintf(buffer, "%d", x);
// say x was 128, buffer now contains [0] = '1', [1] = '2', [2] = '8', [3] = NUL.
Upvotes: 6
Reputation: 4887
If you mean to get the char representation of the integer digits 1, 2, 3, 4, 5, 6, 7, 8, 9 and 0, you can simply do it like this:
char ToChar(int value)
{
assert(value >= 0 && value <= 9);
return '0' + value;
}
If you want to include hexadecimal digits into the mix, you can do this:
char ToChar(int value)
{
assert(value >= 0 && value <= 15);
return value < 10 ? '0' + value : 'a' + value - 10;
}
This will only work though, if the characters are ordered from '0' to '9' in your character set. I have never heard of a character set that doesn't have this property.
Upvotes: 0
Reputation: 26094
The simple answer would be:
(char)my_int;
However, a simple char
might not really be what you want. In C, there are ´signed char´, ´unsigned char´, and "plain" char
. Unfortunately, it is implementation defined if a plain char
is signed or unsigned. So, if you plan to use the down-casts integer in an environment where this matters, make sure to pick the correct char type.
Upvotes: 1