Onde está a função itoa no Linux?

itoa() é uma função realmente útil para converter um número para uma string. O Linux não parece ter itoa(), existe uma função equivalente ou tenho de usar sprintf(str, "%d", num)?

 118
Author: David Guyon, 2008-10-10

16 answers

EDIT: desculpa, eu devia ter-me lembrado que esta máquina é decididamente não-padrão, tendo ligado várias implementações não-padrão libc para fins académicos; -)

Como itoa() é realmente não-padrão, como mencionado por vários comentaristas úteis, é melhor usar {[[5]} ou (melhor ainda, porque é seguro de estouros de buffer) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int). Eu sei que não é tão conciso ou legal quanto itoa(), mas pelo menos você pode escrever uma vez, correr em todos os lugares (tm); -)

Aqui está o velho (editado) resposta

Você está correto ao afirmar que o padrão gcc libc não inclui itoa(), como várias outras plataformas, devido a não ser tecnicamente uma parte do padrão. Veja aqui para um pouco mais de informação. Note que você tem que

#include <stdlib.h>

Claro que já sabes isso, porque querias usar itoa() no Linux depois de presumivelmente usá-lo em outra plataforma, mas... o código (roubado do link acima) iria olhar tipo:

Exemplo

/* 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;
}

Resultado:

Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110
Espero que isto ajude!
 82
Author: Matt J, 2010-01-07 23:36:43

Se você está chamando isso muito, o conselho de "Basta usar snprintf" pode ser irritante. Então aqui está o que você provavelmente quer:

const char *my_itoa_buf(char *buf, size_t len, int num)
{
  static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */

  if (!buf)
  {
    buf = loc_buf;
    len = sizeof(loc_buf);
  }

  if (snprintf(buf, len, "%d", num) == -1)
    return ""; /* or whatever */

  return buf;
}

const char *my_itoa(int num)
{ return my_itoa_buf(NULL, 0, num); }
 12
Author: James Antill, 2008-10-10 19:19:46

Edit: acabei de saber sobre std::to_string o que é idêntico em operação à minha função abaixo. Ele foi introduzido em C++11 e está disponível em versões recentes do gcc, pelo menos tão cedo quanto 4.5 se você ativar as extensões C++0x.


Não só está faltando itoa do gcc, como não é a função mais apropriada para usar, uma vez que você precisa alimentá-lo com um buffer. Precisava de algo que pudesse ser usado numa expressão, por isso inventei isto.:
std::string itos(int n)
{
   const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;
   char buffer[max_size] = {0};
   sprintf(buffer, "%d", n);
   return std::string(buffer);
}
Normalmente seria é mais seguro Utilizar snprintf em vez de sprintf, mas o tampão é cuidadosamente dimensionado para ser imune à superação.

Ver um exemplo: http://ideone.com/mKmZVE

 7
Author: Mark Ransom, 2012-11-16 03:30:24

Como Matt J escreveu, Há {[[0]}, mas não é padrão. O seu código será mais portátil se utilizar snprintf.

 6
Author: Mark, 2014-09-24 13:55:38

itoa não é uma função C padrão. Você pode implementar o seu próprio. Apareceu na primeira edição de "Kernighan" e "Ritchie". a linguagem de Programação C , na página 60. A segunda edição da linguagem de Programação C ("K&R2") contém a seguinte implementação de itoa, na página 64. O Livro nota várias questões com esta implementação, incluindo o fato de que ele não lida corretamente com o número mais negativo

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
}  

A função reverse usada acima é implementada duas páginas antes:

 #include <string.h>

 /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
}  
 6
Author: haccks, 2016-04-03 21:15:33

A seguir à função aloca apenas memória suficiente para manter a representação de texto do número dado e, em seguida, Escreve a representação de texto nesta área usando o método padrão sprintf.

char *itoa(long n)
{
    int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
    if (n<0) len++; // room for negative sign '-'

    char    *buf = calloc(sizeof(char), len+1); // +1 for null
    snprintf(buf, len+1, "%ld", n);
    return   buf;
}
Não se esqueça da memória alocada quando estiver sem necessidade.
char *num_str = itoa(123456789L);
// ... 
free(num_str);

N. B. As snprintf copies n-1 bytes, we have to call snprintf(buf, len+1, "%ld", n) (not just snprintf(buf, len, "%ld", n))

 3
Author: mmdemirbas, 2015-12-20 21:50:13
Aqui está uma versão muito melhorada da solução de Archana. Funciona para qualquer radix 1-16, e números
static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";

static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    for (int index = 0; index < (len / 2); index++)
    {
        char ch = buffer[index];
        buffer[index] = buffer[len - index - 1];
        buffer[len - index - 1] = ch;
    }
}

static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    if (radix == 10)
    {
        if (len < (bufferSize - 1))
        {
            buffer[len++] = '-';
            buffer[len] = '\0';
        }
    }
    else
    {
        int twosCompIndex = 0;
        for (int index = 0; index < len; index++)
        {
            if ((buffer[index] >= '0') && (buffer[index] <= '9'))
            {
                twosCompIndex = buffer[index] - '0';
            }
            else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
            {
                twosCompIndex = buffer[index] - 'A' + 10;
            }
            else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
            {
                twosCompIndex = buffer[index] - 'a' + 10;
            }
            twosCompIndex += (16 - radix);
            buffer[index] = _twosComp[twosCompIndex];
        }
        if (len < (bufferSize - 1))
        {
            buffer[len++] = _numberSystem[radix - 1];
            buffer[len] = 0;
        }
    }
    return len;
}

static int twosNegation(const int x, const int radix)
{
    int n = x;
    if (x < 0)
    {
        if (radix == 10)
        {
            n = -x;
        }
        else
        {
            n = ~x;
        }
    }
    return n;
}

static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
    int strlen = 0;
    int n = twosNegation(x, radix);
    int nuberSystemIndex = 0;

    if (radix <= 16)
    {
        do
        {
            if (strlen < (bufferSize - 1))
            {
                nuberSystemIndex = (n % radix);
                buffer[strlen++] = _numberSystem[nuberSystemIndex];
                buffer[strlen] = '\0';
                n = n / radix;
            }
            else
            {
                break;
            }
        } while (n != 0);
        if (x < 0)
        {
            strlen = negateBuffer(buffer, bufferSize, strlen, radix);
        }
        safestrrev(buffer, bufferSize, strlen);
        return buffer;
    }
    return NULL;
}
 2
Author: Chris Desjardins, 2013-04-16 16:49:09

Onde está a função itoa no Linux?

Não existe tal função no Linux. Em vez disso, uso este código.

/*
=============
itoa

Convert integer to string

PARAMS:
- value     A 64-bit number to convert
- str       Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.
- radix     Radix must be in range -36 .. 36. Negative values used for signed numbers.
=============
*/

char* itoa (unsigned long long  value,  char str[],  int radix)
{
    char        buf [66];
    char*       dest = buf + sizeof(buf);
    boolean     sign = false;

    if (value == 0) {
        memcpy (str, "0", 2);
        return str;
    }

    if (radix < 0) {
        radix = -radix;
        if ( (long long) value < 0) {
            value = -value;
            sign = true;
        }
    }

    *--dest = '\0';

    switch (radix)
    {
    case 16:
        while (value) {
            * --dest = '0' + (value & 0xF);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value >>= 4;
        }
        break;
    case 10:
        while (value) {
            *--dest = '0' + (value % 10);
            value /= 10;
        }
        break;

    case 8:
        while (value) {
            *--dest = '0' + (value & 7);
            value >>= 3;
        }
        break;

    case 2:
        while (value) {
            *--dest = '0' + (value & 1);
            value >>= 1;
        }
        break;

    default:            // The slow version, but universal
        while (value) {
            *--dest = '0' + (value % radix);
            if (*dest > '9') *dest += 'A' - '9' - 1;
            value /= radix;
        }
        break;
    }

    if (sign) *--dest = '-';

    memcpy (str, dest, buf +sizeof(buf) - dest);
    return str;
}
 2
Author: rick-rick-rick, 2017-11-27 12:10:13

Cópia directa para buffer: 64 bits inteiro itoa hex:

    char* itoah(long num, char* s, int len)
    {
            long n, m = 16;
            int i = 16+2;
            int shift = 'a'- ('9'+1);


            if(!s || len < 1)
                    return 0;

            n = num < 0 ? -1 : 1;
            n = n * num;

            len = len > i ? i : len;
            i = len < i ? len : i;

            s[i-1] = 0;
            i--;

            if(!num)
            {
                    if(len < 2)
                            return &s[i];

                    s[i-1]='0';
                    return &s[i-1];
            }

            while(i && n)
            {
                    s[i-1] = n % m + '0';

                    if (s[i-1] > '9')
                            s[i-1] += shift ;

                    n = n/m;
                    i--;
            }

            if(num < 0)
            {
                    if(i)
                    {
                            s[i-1] = '-';
                            i--;
                    }
            }

            return &s[i];
    }

Nota: mude o tempo para o longo para a máquina de 32 bits. longo A inteiro no caso de 32 bits inteiro. m é o radix. Ao diminuir o radix, aumente o número de caracteres (variável i). Ao aumentar o radix, diminuir o número de caracteres (melhor). No caso de um tipo de dados não assinado, Eu apenas se torna 16 + 1.

 1
Author: the sudhakar, 2013-01-19 03:54:51

Eu tentei minha própria implementação do itoa (), parece que é trabalho em binário, octal, decimal e hex

#define INT_LEN (10)
#define HEX_LEN (8)
#define BIN_LEN (32)
#define OCT_LEN (11)

static char *  my_itoa ( int value, char * str, int base )
{
    int i,n =2,tmp;
    char buf[BIN_LEN+1];


    switch(base)
    {
        case 16:
            for(i = 0;i<HEX_LEN;++i)
            {
                if(value/base>0)
                {
                    n++;
                }
            }
            snprintf(str, n, "%x" ,value);
            break;
        case 10:
            for(i = 0;i<INT_LEN;++i)
            {
                if(value/base>0)
                {
                    n++;
                }
            }
            snprintf(str, n, "%d" ,value);
            break;
        case 8:
            for(i = 0;i<OCT_LEN;++i)
            {
                if(value/base>0)
                {
                    n++;
                }
            }
            snprintf(str, n, "%o" ,value);
            break;
        case 2:
            for(i = 0,tmp = value;i<BIN_LEN;++i)
            {
                if(tmp/base>0)
                {
                    n++;
                }
                tmp/=base;
            }
            for(i = 1 ,tmp = value; i<n;++i)
            {
                if(tmp%2 != 0)
                {
                    buf[n-i-1] ='1';
                }
                else
                {
                    buf[n-i-1] ='0';
                }
                tmp/=base;
            }
            buf[n-1] = '\0';
            strcpy(str,buf);
            break;
        default:
            return NULL;
    }
    return str;
}
 1
Author: waaagh, 2013-04-19 01:13:57

Se apenas quiser imprimi-las:

void binary(unsigned int n)
{
    for(int shift=sizeof(int)*8-1;shift>=0;shift--)
    {
       if (n >> shift & 1)
         printf("1");
       else
         printf("0");

    }
    printf("\n");
} 
 1
Author: Andres Romero, 2014-01-16 17:40:33
Ler o código dos tipos que o fazem para ganhar a vida leva-nos a um longo caminho. Vê como é que os tipos do MySQL o fizeram. A fonte está muito bem comentada e vai ensinar-lhe muito mais do que soluções hackeadas encontradas por todo o lado.

Implementação do int2str por MySQL

Eu forneço a implementação mencionada aqui; o link está aqui para referência e deve ser usado para ler a implementação completa.

char *
int2str(long int val, char *dst, int radix, 
        int upcase)
{
  char buffer[65];
  char *p;
  long int new_val;
  char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;
  ulong uval= (ulong) val;

  if (radix < 0)
  {
    if (radix < -36 || radix > -2)
      return NullS;
    if (val < 0)
    {
      *dst++ = '-';
      /* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */
      uval = (ulong)0 - uval;
    }
    radix = -radix;
  }
  else if (radix > 36 || radix < 2)
    return NullS;

  /*
    The slightly contorted code which follows is due to the fact that
    few machines directly support unsigned long / and %.  Certainly
    the VAX C compiler generates a subroutine call.  In the interests
    of efficiency (hollow laugh) I let this happen for the first digit
    only; after that "val" will be in range so that signed integer
    division will do.  Sorry 'bout that.  CHECK THE CODE PRODUCED BY
    YOUR C COMPILER.  The first % and / should be unsigned, the second
    % and / signed, but C compilers tend to be extraordinarily
    sensitive to minor details of style.  This works on a VAX, that's
    all I claim for it.
  */
  p = &buffer[sizeof(buffer)-1];
  *p = '\0';
  new_val= uval / (ulong) radix;
  *--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];
  val = new_val;
  while (val != 0)
  {
    ldiv_t res;
    res=ldiv(val,radix);
    *--p = dig_vec[res.rem];
    val= res.quot;
  }
  while ((*dst++ = *p++) != 0) ;
  return dst-1;
}
 1
Author: Vlatko Šurlan, 2016-04-04 12:02:30

Onde está a função itoa no Linux?

Como itoa() não é padrão em C, Existem várias versões com várias assinaturas de funções.
char *itoa(int value, char *str, int base); é comum em * nix.

Se estiver em falta no Linux ou se o código não quiser limitar a portabilidade, o código pode torná-lo próprio.

Abaixo está uma versão que não tem problemas com INT_MIN e lida com os 'buffers' de problemas: NULL ou um 'buffer' insuficiente devolve NULL.

#include <stdlib.h>
#include <limits.h>
#include <string.h>

// Buffer sized for a decimal string of a `signed int`, 28/93 > log10(2)
#define SIGNED_PRINT_SIZE(object)  ((sizeof(object) * CHAR_BIT - 1)* 28 / 93 + 3)

char *itoa_x(int number, char *dest, size_t dest_size) {
  if (dest == NULL) {
    return NULL;
  }

  char buf[SIGNED_PRINT_SIZE(number)];
  char *p = &buf[sizeof buf - 1];

  // Work with negative absolute value
  int neg_num = number < 0 ? number : -number;

  // Form string
  *p = '\0';
  do {
    *--p = (char) ('0' - neg_num % 10);
    neg_num /= 10;
  } while (neg_num);
  if (number < 0) {
    *--p = '-';
  }

  // Copy string
  size_t src_size = (size_t) (&buf[sizeof buf] - p);
  if (src_size > dest_size) {
    // Not enough room
    return NULL;
  }
  return memcpy(dest, p, src_size);
}

Abaixo encontra-se um C99 ou versão posterior que lida com qualquer base [2...36]

char *itoa_x(int number, char *dest, size_t dest_size, int base) {
  if (dest == NULL || base < 2 || base > 36) {
    return NULL;
  }

  char buf[sizeof number * CHAR_BIT + 2]; // worst case: itoa(INT_MIN,,,2)
  char *p = &buf[sizeof buf - 1];

  // Work with negative absolute value to avoid UB of `abs(INT_MIN)`
  int neg_num = number < 0 ? number : -number;

  // Form string
  *p = '\0';
  do {
    *--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-(neg_num % base)];
    neg_num /= base;
  } while (neg_num);
  if (number < 0) {
    *--p = '-';
  }

  // Copy string
  size_t src_size = (size_t) (&buf[sizeof buf] - p);
  if (src_size > dest_size) {
    // Not enough room
    return NULL;
  }
  return memcpy(dest, p, src_size);
}

Para um código C89 e em frente, substituir o circuito interno por

  div_t qr;
  do {
    qr = div(neg_num, base);
    *--p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[-qr.rem];
    neg_num = qr.quot;
  } while (neg_num);
 1
Author: chux, 2018-05-09 18:46:22

Eu usei _itoa(...) on RedHat 6 and GCC compiler. Funciona.

 0
Author: m_pGladiator, 2008-10-10 15:46:42

Implementação interna da Glibc

A Glibc 2, 28 tem uma implementação interna:

Que é usado em vários lugares internamente, mas eu não poderia encontrar se ele pode ser exposto ou como.

Pelo menos deve ser uma implementação robusta se estiver disposto a extraí-la.

Esta pergunta Pergunta Pergunta Como rolar o seu próprio: Como converter um int para uma cadeia de caracteres em C

Pode usar este programa em vez de sprintf.

void itochar(int x, char *buffer, int radix);

int main()
{
    char buffer[10];
    itochar(725, buffer, 10);
    printf ("\n %s \n", buffer);
    return 0;
}

void itochar(int x, char *buffer, int radix)
{
    int i = 0 , n,s;
    n = s;
    while (n > 0)
    {
        s = n%radix;
        n = n/radix;
        buffer[i++] = '0' + s;
    }
    buffer[i] = '\0';
    strrev(buffer);
}
 -4
Author: Archana Chatterjee, 2012-09-30 01:35:08