将有符号整数数组转换为char数组

时间:2016-11-16 18:00:28

标签: c

我正在尝试将有符号整数数组转换为字符指针。我写了一个样本程序,如下所示。 预期产量为“10-26357-35” 请帮帮我。

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
   int16_t frame_i[5] = {10, -26, 35, 7, -35};
   size_t i;
   char *s = malloc(5*2+1);
   for(i = 0; i<5; i++) {
    snprintf(s + i * 2, 3, "%hd", frame_i[i]);
   }
   return 0;
}

2 个答案:

答案 0 :(得分:2)

你必须考虑到这个标志。换句话说 - 你不能只假设所有数字都是2个字符宽度。

尝试类似:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
   int16_t frame_i[5] = {10, -26, 35, 7, -35};
   size_t i;
   char *s = malloc(5*3+1);  // Allocate memory to hold 3 chars for each number

   char *tmp = s;            // Add a tmp pointer to know how far you are

   for(i = 0; i<5; i++) {
    if (frame_i[i] >= 0)     // Check the sign
    {
        snprintf(tmp, 3, "%02hd", frame_i[i]);  // Requires 2 chars
        tmp += 2;
    }
    else
    {
        snprintf(tmp, 4, "%03hd", frame_i[i]);   // Requires 3 chars
        tmp += 3;
    }
   }

   // Print the result
   printf("%s\n", s);

   // Release memory
   free(s);

   return 0;
}

请注意,该解决方案仅适用于-99到99范围内的数字,并且它会将0放在数字前面-9到9之间。

通过利用0返回打印的字符数,可以获得处理范围更广且不在前面添加snprintf的更通用(且更简单)的解决方案。类似的东西:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STRING_SIZE 1000

int main(void) {
   int16_t frame_i[5] = {10, -26, 35, 7, -35};
   size_t i;
   int size_available = MAX_STRING_SIZE;
   int cnt;
   char *s = malloc(MAX_STRING_SIZE);
   char *tmp = s;
   for(i = 0; i<5; i++) {
    cnt = snprintf(tmp, size_available, "%hd", frame_i[i]);
    if (cnt <= 0 || cnt >= size_available)
    {
        printf("Error - snprintf failed or string too short\n");
        free(s);
        return(0);
    }
    size_available -= cnt;
    tmp += cnt;
   }
   printf("%s\n", s);
   free(s);
   return 0;
}

答案 1 :(得分:0)

以下是您需要做的事情:

  • 为字符串分配空间时,为每个数组元素提供6个字节,因为在带符号的16位整数(例如,-32768)中最多可以有6个数字,并且您将数字存储为字符,而不是数字
  • 您必须根据数字的数字长度调整下一个写入位置。
  • 请记住,当您使用snprintf时,字符串中的未写入字符将为'\0',因此如果您在写入字符串时在字符串中留下空白,则不会获得连续字符串。
  • 另请注意,snprintf中的第二个参数值n必须大于您要放置的最大宽度编号(适用于'\0'

这适用于你的案例:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
       int16_t frame_i[5] = {10, -26, 35, 7, -35};
       size_t i, j;
       char *s = malloc(5*3+1);
       for(i = 0, j=0; i<5; i++) {
           snprintf(s + j, 4, "%hd", frame_i[i]);
           if(frame_i[i]<0 && frame_i[i]<=-10)
                j+=3;
           else if(frame_i[i]<0)
                j+=2;
           else if(frame_i[i] < 10)
                j+=1;
           else
                j+=2;
       }
       printf("%s",s);
       return 0;
}