转换一个十进制转换为任何板蓝根基地号码? [英] Converting a Decimal to Any Radix Base Number?

查看:119
本文介绍了转换一个十进制转换为任何板蓝根基地号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道与strtoll但就是将任何板蓝根基地数(2和36之间),以十进制,我需要通过转换为十进制板蓝根任何碱值,

I know about 'strtoll' but that is converting any Radix Base Number (between 2 and 36) to Decimal and I need to do the opposite by converting Decimal to Any Radix Base Number,

一个例子是十进制130基数12 = AA

an example would be decimal 130 radix 12 = AA

推荐答案

以下code。使用它临时缓冲区建立字符串,然后返回一个重复做。该字符串从末尾向后工作,并通过索引到另一个字符串中设置每个数字建成。这应该是比所有反复短字符串复制和追加的Java版本确实更加高效。你需要免费的,当你与他们做返回的字符串和检查NULL回报,如果有任何机会的基数可能会超出范围......避免分配新的字符串所有的时间,你可能要适应它使用缓冲区里供应的结果。

The following code does it using a temporary buffer to build the string, then returning a duplicate. The string is built by working backwards from the end and setting each digits by indexing into another string. That should be much more efficient than all that repeated short string copying and appending the Java version does. You need to free the returned strings when you're done with them and check for NULL return if there's any chance the radix might be out of range... to avoid allocating new strings all the time you might want to adapt it to use a buffer you supply for the result.

/* return string representation of num in base rad as new string (or NULL) */
char *toBaseWhatever(int num, int rad)
{
    char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    int i;
    char buf[66];   /* enough space for any 64-bit in base 2 */

    /* bounds check for radix */
    if (rad < 2 || rad > 62)
        return NULL;
    /* if num is zero */
    if (!num)
        return strdup("0");

    /* null terminate buf, and set i at end */
    buf[65] = '\0';
    i = 65;

    if (num > 0) {  /* if positive... */
        while (num) { /* until num is 0... */
            /* go left 1 digit, divide by radix, and set digit to remainder */
            buf[--i] = digits[num % rad];
            num /= rad;
        }
    } else {    /* same for negative, but negate the modulus and prefix a '-' */
        while (num) {
            buf[--i] = digits[-(num % rad)];
            num /= rad;
        }
        buf[--i] = '-';
    }   
    /* return a duplicate of the used portion of buf */
    return strdup(buf + i);
}

这篇关于转换一个十进制转换为任何板蓝根基地号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆