开发者

C++ base conversion

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

itoa(word,aux,2);

But G开发者_如何学CCC doesn't recognize itoa. How can I do this conversion to base 2 on a C++ way?

Thanks ;)


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.


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


There is a page of itoa implementations here


what about boost::lexical_cast ???

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜