C语言如何实现整形转换成字符型然后赋值到字符数组

如何实现 将int a=120 变成 char b[4]="120"

a=12345678 为int型,在内存中占4字节,共32位,即为 00000000 10111100 01100001 01001110
将a右移24位即取出前8位,第一个字节;
将a右移16位,然后位与00000000 11111111 即0xff,即可取出第二个字节;
将a右移8位,然后位与00000000 00000000 11111111 即0xff,即可取出第三个字节;
将a位与00000000 00000000 00000000 11111111 即0xff,即可取出第四个字节。

#include <stdio.h>

int main(void)
{
int a = 120;
char b[4];

b[0] = a >> 24;
b[1] = ((a >> 16) & 0xff);
b[2] = ((a >> 8) & 0xff);
b[3] = a & 0xff;

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-05
sprintf(str, "%d ", iNumber); //把数字转换为字符串了

具体实现:
#include<stdio.h>

void main()
{
int a=120;
char b[4];
sprintf(b, "%d ", a);
printf("%s\n",b);
}本回答被提问者采纳
第2个回答  2010-07-07
用强制 类型转换
比如 int a =120;
char b;
b=(char)a;
此时 b 中数据就是char型了
第3个回答  2010-07-07
#include <stdio.h>
#include <stdlib.h>

void main()
{
long int a=120;
char *p,b[10];
int i=0;
p=b;
p=ltoa(a,p,10);

for(i=0;b[i]!='\0';i++)
printf("%2c",b[i]);

}
第4个回答  2010-07-07
b[0] = 120/100%100 + '0'
b[1] = 120/10%10 + '0'
b[2] = 120%1 + '0'
b[3] = '\0'
相似回答