admin管理员组

文章数量:1794759

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

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;

 }

本文标签: 语言八进制十六进制