Home > C, Code > C++ itoa

C++ itoa

It’s super annoying that c/c++ has an atoi function but not an itoa. I’ve had to implement this countless times in my code, and I have a nice snipet that has worked well for me. This function supports output in an base from 2 to 16, and has a “pad” option that add a leading “0″ if the number of chars in the output string are not a multiple of two. This is nice for hex formatting.

string itoa(int value, int base, bool pad){
    enum { kMaxDigits = 35 };
    string buf;
    buf.reserve( kMaxDigits);

    //check that the base is valid
    if(base < 2 || base > 16) return buf;
    int quotient = value;

    //translate number to string with base
    do{
        buf += “0123456789abcdef”[std::abs( quotient % base )];
        quotient /= base;
    } while( quotient );

    //append negative sign for base 10
    if(value <0 && base == 10) buf += '-';

    reverse( buf.begin(), buf.end() );

    if(pad && base != 10) if(buf.length()%2 == 1) buf = "0" + buf;

    return buf;
} 
Categories: C, Code Tags:
  1. No comments yet.

Powered by WP Hashcash