0

我正在做一个学校项目,这个问题出现了。顺便说一句,我不能使用图书馆。

如何将 int 变量转换为 char 数组?我已经尝试过,但它没有用,尝试了很多其他的东西,甚至魔法也不起作用......

char *r = malloc(sizeof(char*));
int i = 1;
r[counter++] = (char) i;

有人能帮我吗?感谢您的时间。

4

7 回答 7

1

In your code, you should allocate for char size and not char *. Please try with this code segment

char *r = malloc(sizeof(char) * N); // Modified here
int i = 1;
r[counter++] = i & 0xff; // To store only the lower 8 bits.
于 2013-03-24T00:58:57.217 回答
0

You could also try this:

char *r = malloc(sizeof(char));
char *s = (char*)&i; 
r[counter++] = s[0];

This is an other funny way to proceed and it allows you to access the full int with: s[0], s[1], etc...

于 2013-03-24T01:01:14.647 回答
0

嗯...下面的代码有什么问题

char *r = malloc(sizeof(char) * ARR_SIZE);
int i = 1;
sprintf(r,"%d",i);

printf("int %d converted int %s",i,r);

它现在对你有用吗

于 2013-05-13T16:17:08.390 回答
0

如果你不能使用这个库,你就不能使用malloc.

但这会起作用:

int i = 0;
char *p = (char *)&i;
p[0] = 'H';
p[1] = 'i';
p[2] = '!';
p[3] = '\0';
printf("%s\n", p);

假设您int是 32 位或更多(而您char是 8 位)。

然后,如果您有:

int i[100];

char您可以将其视为大小等于的数组sizeof (i)。IE

int i[100];
int sz = sizeof(i);     // probably 400
char *p = (char *)i;    // p[0] to p[sz - 1] is valid.
于 2013-03-24T01:05:06.707 回答
0

如果您不想包含数学库:

unsigned long pow10(int n);

void main(){
    char test[6] = {0};
    unsigned int testint = 2410;
    char conversion_started = 0;
    int i=0,j=0;float k=0;
    for(i=sizeof(test);i>-1;i--){
        k=testint/pow10(i);
        if(k<1 && conversion_started==0) continue;
        if(k >= 0 && k < 10){
            test[j++]=k+0x30;
            testint = testint - (k * pow10(i));
            conversion_started=1;
        }
    }
    test[j]=0x00;
    printf("%s",test);
}

unsigned long pow10(int n){
    long r = 1;
    int q = 0;
    if(n==0) return 1;
    if(n>0){
        for(q=0;q<n;q++) r = r * 10;
        return r;
    }
}

注意:我不太关心 char 数组的长度,所以你最好明智地选择它。

于 2013-03-24T01:46:44.257 回答
0

您可以使用 aunion代替。假设sizeof int == 4,

typedef union {
    int i;
    char[4] cs;
} int_char;

int_char int_char_pun;
int_char_pun.i = 4;
for (int i = 0; i < 4; i++) {
    putchar(int_char_pun.cs[i]);
}

当心; int_char.cs 通常不是以 null 结尾的字符串,或者它可能是,但长度 < 4。

于 2013-03-24T01:18:59.717 回答
0

你介意失去精度吗?char 通常是 8 位,而 int 通常更多。任何超过 255 的 int 值都将转换为其模 255 - 除非您想将 int 转换为容纳 int 所需的尽可能多的字符。

你的标题似乎是这样说的,但到目前为止没有一个答案给出。

如果是这样,您需要声明一个 char 数组,它是sizeof(int) / sizeof(char)并循环多次,i >> 8进入r[looop_var]. 根本不需要 malloc,除非你的老师告诉你这样做。在这种情况下,不要忘记处理 malloc 失败。

让我们说一些类似的东西(我正在编码这个没有编译它,所以要小心)

int numChars = sizeof(int) / sizeof(char);
char charArry[numChard];      // or malloc() later, if you must (& check result)
int convertMe = 0x12345678;
int loopVar;

for (loopVar = 0; loopvar < numChars)
{
  charArry[loopVar ] = convertMe ;
  convertMe = convertMe  >> 8;
}
于 2013-03-24T01:11:27.310 回答