Converting a database in C ++

Hi, I am trying to port some code from Windows to Linux. I have it:

itoa(word,aux,2);

But GCC does not recognize itoa. How can I do this conversion to base 2 in C ++?

Thank;)

+5
source share
5 answers

Here ... help

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

You must adapt it to your needs (note that this has 2 arguments, not 3) Also note that the inverse function is also in the wikipedia link.

Also, here are some other cases (but not for base 2)

This function is not defined in ANSI-C and is not part of C ++, but is supported by some compilers.

sprintf:

sprintf(str,"%d",value) .

sprintf(str,"%x",value) .

sprintf(str,"%o",value) .

+2

itoa

+1

, , :

void itoa(int n, char s[], std::size_t base = 10) {
    const char digits[] = "0123456789abcdef";
    int i, sign;

    if (base < 2 || base > 16)
        throw std::invalid_argument("invalid base");
    if ((sign = n) < 0)  /* record sign */
        n = -n;      /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = digits[n % base]; /* get next digit */
    } while ((n /= base) > 0);         /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}
+1

?:)

int convert_base(int v, int b){ 

    if (v == 0) return 0;   
    else 
        return (v%b+10*convert_base(v/b,b));    
}
0

All Articles