任意进制的转换函数

//
//  main.c
//  baseconv
//
//  Created by Cheney Shen on 11-4-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#include <stdio.h>
#include <limits.h>
#include <string.h>

char* baseconv(unsigned long long, int);

int main (int argc, const char * argv[])
{
    printf("the result is %s", baseconv(3942095803582093809, 2));
    return 0;
}

char* baseconv(unsigned long long num, int base) {
    static char retbuf[sizeof(int)*CHAR_BIT + 1];
    char *p;
    
    if(base < 2 || base > 16)
        return NULL;
    
    p = &retbuf[sizeof(retbuf) - 1];
    *p = '\0';
    
    do{
        *--p = "0123456789abcdef"[num % base];
        num /= base;
    } while(num != 0);
    return p;
}
the result is 11011010110101001000110011111101001011000100011001100111110001

转载于:https://www.cnblogs.com/shenfei2031/archive/2011/04/16/2017692.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个将任意进制转换任意进制数的 C++ 代码示例: ```cpp #include <iostream> #include <string> using namespace std; // 将任意进制转换为十进制数 int toDecimal(string num, int base) { int result = 0; int power = 1; int len = num.size(); for (int i = len - 1; i >= 0; i--) { int digit = isdigit(num[i]) ? num[i] - '0' : num[i] - 'A' + 10; if (digit >= base) { cout << "非法输入!" << endl; return -1; } result += digit * power; power *= base; } return result; } // 将十进制转换任意进制数 string fromDecimal(int num, int base) { string result = ""; while (num > 0) { int digit = num % base; char ch = (digit >= 10) ? ('A' + digit - 10) : (digit + '0'); result = ch + result; num /= base; } return result; } // 主函数 int main() { string num; int base1, base2; cout << "请输入要转换的数字:"; cin >> num; cout << "请输入数字的原始进制:"; cin >> base1; cout << "请输入数字要转换进制:"; cin >> base2; int decimal = toDecimal(num, base1); if (decimal == -1) { return 0; } string result = fromDecimal(decimal, base2); cout << num << "(" << base1 << "进制) = " << result << "(" << base2 << "进制)" << endl; return 0; } ``` 该程序首先要求用户输入要转换的数字、数字的原始进制和数字要转换进制。然后,它将使用 `toDecimal` 函数将数字从原始进制转换为十进制,并使用 `fromDecimal` 函数将其转换为指定的进制。最后,程序将打印转换后的数字。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值