C++ base conversion

2019-06-22 09:33发布

问题:

Hello I'm trying to port some code from Windows to Linux. I have this:

itoa(word,aux,2);

But GCC doesn't recognize itoa. How can I do this conversion to base 2 on a C++ way?

Thanks ;)

回答1:

Here´s some 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 should adapt it to your needs (notice this one has 2 arguments, not 3) Also notice the reverse function is also in the wikipedia link.

Additionally, 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.

A standard-compliant alternative for some cases may be sprintf:

sprintf(str,"%d",value) converts to decimal base.

sprintf(str,"%x",value) converts to hexadecimal base.

sprintf(str,"%o",value) converts to octal base.



回答2:

There is a page of itoa implementations here



回答3:

Here is Tom's answer, modified to use the base as your code requires:

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


回答4:

what about boost::lexical_cast ???

http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm



回答5:

What about using the power of recursion? :)

int convert_base(int v, int b){ 

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


标签: c++ base