C语言程序: 将二进制转换成十进制

Write a program in C that converts binary numbers into hexadecimal
numbers (only required to work on positive numbers). The binary numbers are
provided to the program via standard input and are at most 16 bits long. Each
binary line is separated via a return character. Place your answer in the file called
'bin2hex.c' in the Q3 directory. An example of the program running is given below
(input typed by the user is given in bold):
$ ./bin2hex
1111111111111111
0xFFFF
0000000000000000
0x0
0
0x0
10
0x2
1010
0xA
11110000
0xF0
101001011111
0xA5F
01010
0xA
111
0x7

根据要求中的限制,可以直接利用接收字符函数即可实现。代码如下,输入的是0或者1,那么一直转换;直到输入不是0或者1,退出程序。可以直接拷贝,验证正确:

#include<stdio.h>
#include<stdlib.h>
int main()
{
  char ch;
  unsigned int num;

  while( 1 )//一直循环
  {
    num = 0;
    while( (ch = getchar()) != '\n' )
    {
      if ('0' <= ch && ch <= '1')
        num = (num << 1) + ch - '0';
      else
        exit(1);//如果输入的不是0或者1,那么退出程序
    }
    printf("0x%X\n", num);
  }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-07-21
简单方法就是采用字符串映射法,方便实现!
定义一个16个变量的字符数组,分别对应0-15这16个字符。分析串,得到对应的字符即可
第2个回答  2014-07-21
#include <stdio.h>

int Bin2Hex(char binary[]) {
int i,num = 0;
for(i = 0; binary[i]; ++i)
num = 2 * num + binary[i] - '0';
return num;
}

int main() {
char binary[32] = "1010101010001111";
printf("0X%X\n",Bin2Hex(binary));
return 0;
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网