C语言 简单的 int 到 char[] 转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5050067/
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 07:50:58  来源:igfitidea点击:

Simple int to char[] conversion

ccharacter-encoding

提问by Waypoint

I have a simple question

我有一个简单的问题

How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?

如何简单地将整数(获取值 0-8)转换为 char,例如 C 中的 char[2]?

Thanks

谢谢

回答by Yoko Zunna

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}

Hope it will be helpful to you.

希望对你有帮助。

回答by Prashant

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;

itoa(a,arr,10) ;   // itoa() is a function of stdlib.h file that convert integer 
                   // int to array itoa( integer, targated array, base u want to             
                   //convert like decimal have 10 

for( int i= 0 ; i < strlen(arr); i++)   //  strlen()   function in string file thar return string length
  printf("%c",arr[i]);

}

回答by Erik

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

用这个。当心 i 大于 9,因为这些将需要一个包含 2 个以上元素的字符数组以避免缓冲区溢出。

char c[2];
int i=1;
sprintf(c, "%d", i);

回答by xanatos

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

你不能在“标准”C 中真正做到这一点,因为 int 和 char 的大小不是固定的。假设您在英特尔 PC 上使用 Windows 或 Linux 下的编译器...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

记住你的机器的字节序!而那个 int “通常”是 32 位,所以是 4 个字符!

But you probably meant "i want to stringify a number", so ignore this response :-)

但是您可能的意思是“我想对数字进行字符串化”,因此请忽略此回复:-)

回答by ChrisJ

If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:

如果要将 0-9 范围内的 int 转换为 char,通常可以这样写:

int x;
char c = '0' + x;

Now, if you want a character string, just add a terminating '\0' char:

现在,如果你想要一个字符串,只需添加一个终止的 '\0' 字符:

char s[] = {'0' + x, '##代码##'};

Note that:

注意:

  1. You must be sure that the int is in the 0-9 range, otherwise it will fail,
  2. It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.
  1. 一定要确定int在0-9范围内,否则会失败,
  2. 仅当数字的字符代码是连续的时才有效。在绝大多数基于 ASCII 的系统中都是如此,但不能保证在所有情况下都如此。