C语言 C语言中int转char

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46006861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:42:41  来源:igfitidea点击:

Converting int to char in C

ctype-conversion

提问by Kyle Hobbs

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:

现在我正在尝试在 C 编程中将 int 转换为 char。经过研究,我发现我应该可以这样做:

int value = 10;
char result = (char) value;

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:

我想要的是返回'A'(并且0-9返回'0'-'9')但是我认为这会返回一个换行符。我的整个函数如下所示:

char int2char (int radix, int value) {
  if (value < 0 || value >= radix) {
    return '?';
  }

  char result = (char) value;

  return result;
}

回答by P__J__

to convert int to char you do not have to do anything

将 int 转换为 char 你不必做任何事情

char x;
int y;


/* do something */

x = y;

only one int to char value as the printable (usually ASCII) digit like in your example:

只有一个 int 到 char 值作为可打印(通常是 ASCII)数字,如您的示例所示:

const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int inttochar(int val, int base)
{
    return digits[val % base];
}

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 *),则需要使用任何标准函数,例如 sprintf、itoa、ltoa、utoa、ultoa .... 或自己编写一个:

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;
}

回答by Bathsheba

A portableway of doing this would be to define a

一种可移植的方法是定义一个

const char* foo = "0123456789ABC...";

where ...are the rest of the characters that you want to consider.

...您要考虑的其余字符在哪里。

Then and foo[value]will evaluate to a particular char. For example foo[0]will be '0', and foo[10]will be 'A'.

然后 andfoo[value]将评估为特定的char. 例如foo[0]将是'0'foo[10]并将是'A'

If you assume a particular encoding(such as the common but by no means ubiquitous ASCII) then your code is not strictly portable.

如果您采用特定的编码(例如通用但绝不是普遍存在的 ASCII),那么您的代码就不是严格可移植的。

回答by dbush

Characters use an encoding (typically ASCII) to map numbers to a particular character. The codes for the characters '0'to '9'are consecutive, so for values less than 10 you add the value to the character constant '0'. For values 10 or more, you add the value minus 10 to the character constant 'A':

字符使用编码(通常是 ASCII)将数字映射到特定字符。字符'0'to的代码'9'是连续的,因此对于小于 10 的值,您将值添加到字符常量'0'。对于 10 或更多的值,您将值减去 10 添加到字符常量'A'

char result;
if (value >= 10) {
    result = 'A' + value - 10;
} else {
    result = '0' + value;
}

回答by chux - Reinstate Monica

Converting Int to Char

将整数转换为字符

I take it that OP wants more that just a 1 digit conversion as radixwas supplied.

我认为 OP 想要的不仅仅是提供的 1 位数字转换radix



To convert an intinto a string, (not just 1 char) there is the sprintf(buf, "%d", value)approach.

要将 anint转换为string,(不仅仅是 1 char)有一种sprintf(buf, "%d", value)方法。

To do so to any radix, string management becomes an issue as well as dealing the corner case of INT_MIN

要对任何基数这样做,字符串管理成为一个问题以及处理 INT_MIN



The following C99 solution returns a char*whose lifetime is valid to the end of the block. It does so by providing a compound literalvia the macro.

以下 C99 解决方案返回char*其生命周期有效到块末尾的 。它通过宏提供复合文字来实现。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Maximum buffer size needed
#define ITOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 2)

char *itoa_base(char *s, int x, int base) {
  s += ITOA_BASE_N - 1;
  *s = '
void test(int x) {
  printf("base10:% 11d base2:%35s  base36:%7s ", x, TO_BASE(x, 2), TO_BASE(x, 36));
  printf("%ld\n", strtol(TO_BASE(x, 36), NULL, 36));
}

int main(void) {
  test(0);
  test(-1);
  test(42);
  test(INT_MAX);
  test(-INT_MAX);
  test(INT_MIN);
}
'; if (base >= 2 && base <= 36) { int x0 = x; do { *(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[abs(x % base)]; x /= base; } while (x); if (x0 < 0) { *(--s) = '-'; } } return s; } #define TO_BASE(x,b) itoa_base((char [ITOA_BASE_N]){0} , (x), (b))

Sample usage and tests

示例使用和测试

base10:          0 base2:                                  0  base36:      0 0
base10:         -1 base2:                                 -1  base36:     -1 -1
base10:         42 base2:                             101010  base36:     16 42
base10: 2147483647 base2:    1111111111111111111111111111111  base36: ZIK0ZJ 2147483647
base10:-2147483647 base2:   -1111111111111111111111111111111  base36:-ZIK0ZJ -2147483647
base10:-2147483648 base2:  -10000000000000000000000000000000  base36:-ZIK0ZK -2147483648

Output

输出

if(value < 10) return '0'+value;
return 'A'+value-10;


Ref How to use compound literals to fprintf()multiple formatted numbers with arbitrary bases?

Ref如何将复合文字用于fprintf()具有任意基数的多个格式化数字?

回答by savram

Check out the ascii table

查看ascii 表

The values stored in a char are interpreted as the characters corresponding to that table. The value of 10 is a newline

存储在 char 中的值被解释为与该表对应的字符。10 的值是一个换行符

回答by Jonathan Howard

So characters in C are based on ASCII(or UTF-8 which is backwards-compatible with ascii codes). This means that under the hood, "A" is actually the number "65" (except in binary rather than decimal). All a "char" is in C is an integer with enough bytes to represent every ASCII character. If you want to convert an intto a char, you'll need to instruct the computer to interpret the bytes of an int as ASCII values - and it's been a while since I've done C, but I believe the compiler will complain since charholds fewer bytes than int. This means we need a function, as you've written. Thus,

因此,C 中的字符基于ASCII(或与 ascii 代码向后兼容的 UTF-8)。这意味着在引擎盖下,“A”实际上是数字“65”(二进制而不是十进制除外)。C 中的所有“字符”都是一个整数,具有足够的字节来表示每个 ASCII 字符。如果您想将 an 转换int为 a char,您需要指示计算机将 int 的字节解释为 ASCII 值 - 自从我使用 C 以来已经有一段时间了,但我相信编译器会抱怨,因为它char拥有更少字节比int. 这意味着我们需要一个函数,正如你所写的。因此,

##代码##

will be what you want to return from your function. Keep your bounds checks with "radix" as you've done, imho that is good practice in C.

将是您想要从您的函数返回的内容。正如你所做的那样,用“基数”保持你的边界检查,恕我直言,这是 C 中的好习惯。