问题描述
现在我正在尝试在 C 编程中将 int 转换为 char.经过研究,我发现我应该可以这样做:
Right now I am trying to convert an int to a char in C programming. After doing research, I found that I should be able to do it like this:
int value = 10;
char result = (char) value;
我想要的是返回'A'(并且0-9返回'0'-'9')但是我认为这会返回一个换行符.我的整个函数看起来像这样:
What I would like is for this to return 'A' (and for 0-9 to return '0'-'9') but this returns a new line character I think.My whole function looks like this:
char int2char (int radix, int value) {
if (value < 0 || value >= radix) {
return '?';
}
char result = (char) value;
return result;
}
推荐答案
把 int 转换成 char 你什么都不用做
to convert int to char you do not have to do anything
char x;
int y;
/* do something */
x = y;
只有一个 int 到 char 值作为可打印(通常是 ASCII)数字,如您的示例:
only one int to char value as the printable (usually ASCII) digit like in your example:
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int inttochar(int val, int base)
{
return digits[val % base];
}
如果你想转换成字符串 (char *) 那么你需要使用任何标准函数,比如 sprintf, itoa, ltoa, utoa, ultoa .... 或者自己写一个:
if you want to convert to the string (char *) then you need to use any of the stansdard functions like sprintf, itoa, ltoa, utoa, ultoa .... or write one yourself:
char *reverse(char *str);
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *convert(int number, char *buff, int base)
{
char *result = (buff == NULL || base > strlen(digits) || base < 2) ? NULL : buff;
char sign = 0;
if (number < 0)
{
sign = '-';
}
if (result != NULL)
{
do
{
*buff++ = digits[abs(number % (base ))];
number /= base;
} while (number);
if(sign) *buff++ = sign;
if (!*result) *buff++ = '0';
*buff = 0;
reverse(result);
}
return result;
}
这篇关于C语言中int转char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!