Demo entry 1463098

itoa

   

Submitted by anonymous on Mar 04, 2015 at 21:01
Language: C++. Code size: 2.0 kB.

//
// int_to_ascii
//
//    http://hhsprings.pinoko.jp/site-hhs/2015/02/itoa%E3%81%94%E3%81%A8%E3%81%8D/
//
#ifndef __INT_TO_ASCII_H_B60523C31AAC4482A753425514AE85D7__
#define __INT_TO_ASCII_H_B60523C31AAC4482A753425514AE85D7__ /*DEFINED, BUT EMPTY*/

//#include <type_traits> // for make_signed
//make_signed short-cut version... (for VS8)
template<typename UType_> struct _make_signed {
};
template<> struct _make_signed<char> {
    typedef signed char type;
};
template<> struct _make_signed<unsigned char> {
    typedef signed char type;
};
template<> struct _make_signed<unsigned short> {
    typedef signed short type;
};
template<> struct _make_signed<unsigned int> {
    typedef signed int type;
};
template<> struct _make_signed<unsigned long> {
    typedef signed long type;
};
template<> struct _make_signed<unsigned long long> {
    typedef signed long long type;
};

#include <algorithm>

namespace utils {

    template<typename ULongType_,
             typename CharT_,
             unsigned radix,
             size_t bufsiz> inline
        CharT_* int_to_ascii(ULongType_ val, CharT_ *buf, bool is_negative)
    {
        typedef typename _make_signed<ULongType_>::type LongType_;
        CharT_ *p = buf;
        size_t length = 0;
        if (is_negative) {
            *p++ = CharT_('-');
            length++;
            val = (ULongType_)(-(LongType_)val);
        }
        CharT_ *firstdig = p;
        unsigned digval;
        do {
            digval = (unsigned) (val % radix);
            val /= radix;
            if (digval > 9) {
                *p++ = (CharT_) (digval - 10 + CharT_('a'));
            } else {
                *p++ = (CharT_) (digval + CharT_('0'));
            }
            length++;
        } while (val > 0 && length < bufsiz);
        do {
            std::swap(*--p, *firstdig++);
        } while (firstdig < p);
        return buf + length;
    }

}

#endif // ifndef __INT_TO_ASCII_H_B60523C31AAC4482A753425514AE85D7__

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).