How to convert int into char* in C (without sprintf)

半世苍凉 提交于 2020-01-14 06:49:38

问题


some day, i wanted to convert in C an integer into a char *, this int can be negative.

I wasn't able to use sprintf ,snprintf neither, so how do i do that ?


回答1:


To roll one's own itoa()-like function, first one must address how to handle memory. The easiest is to use a large-enough memory for all possible int values (INT_MIN).

The buffer required size is mathematically ceiling(log10(-INT_MIN))+3. This can be approximated with:

#include <limits.h>
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT/3 + 3)

Then build the digits up one-by-one starting with the least significant digit using %10 and then /10 to reduce the value.

By using a do loop, code catches the corner case of x==0 as at least one digit is made.

This code avoids if (x < 0) { x = -x; ... as negating INT_MIN (or multiplying by -1 leads to int overflow, which is UB.

#include <limits.h>
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT/3 + 3)

char *my_itoa(char *dest, size_t size, int x) {
  char buf[INT_STR_SIZE];
  char *p = &buf[INT_STR_SIZE - 1];
  *p = '\0';
  int i = x;

  do {
    *(--p) = abs(i%10) + '0';
    i /= 10;
  } while (i);

  if (x < 0) {
    *(--p) = '-';
  }
  size_t len = (size_t) (&buf[INT_STR_SIZE] - p);
  if (len > size) {
    return NULL;  // Not enough room
  }
  return memcpy(dest, p, len);
}

With C99 or later, code can handle the buffer creation with a compound literal allowing separate buffers for each mt_itoa() call.

// compound literal C99 or later
#define MY_ITOA(x) my_itoa((char [INT_STR_SIZE]){""}, INT_STR_SIZE, x)

int main(void) {
  printf("%s %s %s %s\n", MY_ITOA(INT_MIN), MY_ITOA(-1), MY_ITOA(0), MY_ITOA(INT_MAX));
  return (0);
}

Output

-2147483648 -1 0 2147483647



回答2:


to convert from integer to char* use the function itoa(). /* itoa example */

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

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}



回答3:


So, i made a function who make the job

EDIT: there is a leaks, and the function is a little bit dirty i agree with that...

Create a file my_int_char.c, containing the following:

#include <stdlib.h>

char    *my_int_char(int nbr)
{
  char  *tab = malloc(sizeof(char) * 16);
  int   count = 0, div=1, neg = 0, c = 0, tmp_div = 1;
  if (nbr < 0)
    {
      nbr *= -1;
      neg = 1;
    }
  while (nbr / tmp_div >= 1)
    {
      tmp_div *= 10;
      c++;
    }
  while (c >= count && (c - (count + 1)) >= 0)
    {
      tab[c - (count + 1)] = nbr / div % 10 + 48;
      div *= 10;
      ++count;
    }
  if (neg)
    {
      while (c >= 0)
        {
          tab[c + 1] = tab[c];
          c--;
        }
      tab[0] = '-';
    }
  return (tab);
}

there you have it ! now test your function like that in a main;

main()
{
   printf("%s\n", my_int_char(-42));
   printf("%s\n", my_int_char(42));
   printf("%s\n", my_int_char(42021));
   return (0);
}


来源:https://stackoverflow.com/questions/36380105/how-to-convert-int-into-char-in-c-without-sprintf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!