栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

/*

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

/

#include
#include

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指向的位置是'',此时交换之后就会导致''在字符串首位,此时打印字符串时就不会显示字符串
    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 %dn", A, N);
    conversion(A, Bits, N);
    puts(Bits);
    return 0;

 }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012889.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号