zoukankan      html  css  js  c++  java
  • [C++] Linux下的itoa函数

    上篇文章说到linux需要itoa函数,下面我就提供一份跨平台的itoa函数。


    这个函数会返回字符串的长度,在某些场合下会很有用。

    //return the length of result string. support only 10 radix for easy use and better performance
    int my_itoa(int val, char* buf)
    {
        const unsigned int radix = 10;
    
        char* p;
        unsigned int a;        //every digit
        int len;
        char* b;            //start of the digit char
        char temp;
        unsigned int u;
    
        p = buf;
    
        if (val < 0)
        {
            *p++ = '-';
            val = 0 - val;
        }
        u = (unsigned int)val;
    
        b = p;
    
        do
        {
            a = u % radix;
            u /= radix;
    
            *p++ = a + '0';
    
        } while (u > 0);
    
        len = (int)(p - buf);
    
        *p-- = 0;
    
        //swap
        do
        {
            temp = *p;
            *p = *b;
            *b = temp;
            --p;
            ++b;
    
        } while (b < p);
    
        return len;
    }

    这个实现的典型速度大概是180毫秒左右。作为对比,MFC自带的itoa耗时是320毫秒左右。用snprintf的实现就不要出来比速度了,不是一个级别的。


  • 相关阅读:
    枚举类 --单例模式
    模板设计模式
    动态代理
    反射应用--修改属性值
    通过反射绕过泛型
    java反射
    网络编程练习
    TCP编程
    GUI 聊天界面
    UDP传输多线程
  • 原文地址:https://www.cnblogs.com/hehe520/p/6330423.html
Copyright © 2011-2022 走看看