将整数转化为一个任意进制的字符串,将任意进制的字符串转化为一个整数的代码

 

    // 将整数转化为一个任意进制的字符串
    static void int_to_string(int value, char* szDest, int type = 10)
    {
        bool negative = false;
        if (value < 0)
        {
            negative = true;
            value = -value;
        }

        int index = 0;
        int nDecNum;
        char szTmp[128];
        memset(szTmp, 0, 128);
        while (value && index < 128)
        {
            nDecNum = value % type;
            value /= type;
            if (nDecNum < 10)
            {
                szTmp[index] = '0' + nDecNum;
            }
            else
            {
                szTmp[index] = 'A' + nDecNum - 10;
            }
            index++;
        }

        int pos = 0;
        if (negative)
        {
            szDest[pos] = '-';
            pos++;
        }
        for (int i = index - 1; i >= 0; i--)
        {
            szDest[pos] = szTmp[i];
            pos++;
        }
        szDest[pos] = 0;
    }
    static int GetNum(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
        else if (c >= 'a' && c <= 'z')
        {
            return c + 10 - 'a';
        }
        else if (c >= 'A' && c <= 'Z')
        {
            return c + 10 - 'A';
        }
        else
        {
            return -1;
        }
    }

    // 将任意进制的字符串转化为一个整数
    static bool string_to_int(const char* szSrc, int& value, int type = 10)
    {
        value = 0;
        int nDecNum;
        int len = (int)strlen(szSrc);
        int n = 1;
        for(int i = len - 1; i >= 0; i--)
        {
            nDecNum = GetNum(szSrc[i]);
            if (nDecNum == -1)
            {
                return false;
            }
            value += nDecNum * n;
            n *= type;
        }
        
        return true;
    }

 

posted on 2014-01-13 13:41  叶飞影  阅读(1634)  评论(1编辑  收藏  举报