Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ base conversion

Tags:

c++

base

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

like image 242
Rui Avatar asked Jul 11 '10 23:07

Rui


2 Answers

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.

like image 108
Tom Avatar answered Sep 30 '22 01:09

Tom


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);
}
like image 41
Head Geek Avatar answered Sep 30 '22 01:09

Head Geek