C语言实现二进制、八进制、十六进制的转换

/*

         题目要求:输入一个十进制数据,转换为二进制,八进制和十六进制数据并输出转换结果。

/

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

void input(int &a,int &n) {
    printf("Please enter the number you need to caculate and the base conversiom you want!\n");
    scanf_s("%d",&a);
    scanf_s("%d",&n);
}

void conversion(int a,char bits[56],int n) {

    int i;
    int j = 0;
    int k = 0;
    int bit = 0;
#if 1
    while (a) {
        i = a % n;
        if (i > 9)
            bits[k] = i - 10 + 'A';
        else
            bits[k] = i + '0';
        a = a / n;
        k++;
}
    
#endif // 0
#if 0
    switch (n) {
        case 2: bit = 1; break;
        case 8: bit = 3; break;
        case 16:bit = 4; break;
    }
    while (a) {
        j = a & (n - 1);
        if (j > 9)
            bits[k] = j - 10 + 'A';
        else
            bits[k] = j + '0';
        a = a >> bit;
        k++;
    }
    printf("----%s----\n", bits);
#endif // 1
    k--;//k如果不-1,则k指向的位置是'\0',此时交换之后就会导致'\0'在字符串首位,此时打印字符串时就不会显示字符串
    j = 0;//此时j需要初始化为0,使j指向数组首元素的地址再进行比较。
    while (k > j) {
        int temp;
        temp = bits[j];
        bits[j] = bits[k];
        bits[k] = temp;
        k--;
        j++;
//        printf("****%s****\n", bits);
    }
//    printf("++++%s++++\n", bits);
}

int main() {

    char Bits[32] = { '0' };
    int A;
    int N;
    input(A,N);
    printf("\nThe base of the number you input and convert is:%d %d\n", A, N);
    conversion(A, Bits, N);
    puts(Bits);
    return 0;

 }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值