4

Here is code in Java:

int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);

Now I want the same in C++, but all the conversions i find convert to base 10 only. I ofc dont want to implement this by mysleft, why to write something what already exists

kajacx
  • 12,361
  • 5
  • 43
  • 70
  • I had it backwards. Sorry. – Corey Ogburn Dec 06 '13 at 15:30
  • `itoa()` in `` will allow you to specify the base (between 2 - 36).. – Nim Dec 06 '13 at 15:31
  • _don't want to implement this by myself_. I remember this as a common assignment in beginning programming classes, so any real programmer shouldn't consider it a burden. – Barmar Dec 06 '13 at 15:33
  • Implement it yourself. It's relatively simple, so you should know how to do this. What if you had a job interview? After that, you can use something better, but you SHOULD be able to reinvent a simple wheel, even if you will later buy a better-designed wheel. – leewz Dec 06 '13 at 15:39
  • 1
    @Nim, itoa isn't standard C++. It doesn't seem to be standard C either. – leewz Dec 06 '13 at 15:40
  • how do i possible duplicate: http://stackoverflow.com/questions/3225130/c-base-conversion – leewz Dec 06 '13 at 15:41

4 Answers4

2

although std::strtol is more flexible, in a controlled case you can use itoa as well.

int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);
yildirim
  • 316
  • 7
  • 14
1

If you want base 8 or 16 you can easily use the string manipulators std::oct and std::hex. If you want arbitrary bases, I suggest checking out this question.

Community
  • 1
  • 1
KitsuneYMG
  • 12,753
  • 4
  • 37
  • 58
1

Without error handling http://ideone.com/nCj2XG:

char *toString(unsigned int value, unsigned int radix)
{
    char digit[] = "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ";
    char stack[32];
    static char out[33];

    int quot, rem;
    int digits = 0;

    do
    {
        quot = value / radix;
        rem = value % radix;

        stack[digits] = digit[rem];
        value = quot;
        digits++;
    }
    while( value );

    int i = 0;
    while(digits--)
    {
        out[i++] = stack[digits];
    }

    out[i] = 0;

    return out;
}
Artur
  • 7,038
  • 2
  • 25
  • 39
1

There is no standard function itoa, which performs conversion to an arbitrary calculus system. But for example, in my version of the compiler there is no implementation. My solution:

#include <string>

// maximum radix - base36
std::string int2string(unsigned int value, unsigned int radix) {
    const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    while (value > 0) {
        unsigned int remainder = value % radix;
        value /= radix;
        result.insert(result.begin(), base36[remainder]);
    }
    return result;
}