我试图弄清楚为什么这个代码只用2位数的十六进制数字。例如,如果输入“11”,它将输出“00010001”,但如果输入“111”,则会给我一些随机数。我想尽量让它接受用户想要的数字。将十六进制转换为二进制
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void binary_hex(int n, char hex[]);
int hex_binary(char hex[]);
int main()
{
char hex[20],c;
int n;
printf("Enter hexadecimal number: ");
scanf("%s",hex);
printf("Binary number: %d",hex_binary(hex));
system("pause");
return 0;}
//Function to convert hexadecimal to binary.
int hex_binary(char hex[]) {
int i, length, decimal=0, binary=0;
for(length=0; hex[length]!='\0'; ++length);
for(i=0; hex[i]!='\0'; ++i, --length)
{
if(hex[i]>='0' && hex[i]<='9')
decimal+=(hex[i]-'0')*pow(16,length-1);
if(hex[i]>='A' && hex[i]<='F')
decimal+=(hex[i]-55)*pow(16,length-1);
if(hex[i]>='a' && hex[i]<='f')
decimal+=(hex[i]-87)*pow(16,length-1);
}
//At this point, variable decimal contains the hexadecimal number in decimal format.
i=1;
while (decimal!=0)
{
binary+=(decimal%2)*i;
decimal/=2;
i*=10;
}
return binary;
}
工作对我很好。它提供了'100010001'输出'111'输入.. – 2014-10-28 18:00:25
什么“一些随机数”是你的输出? – 2014-10-28 18:06:50
您正在将二进制数存储在'int'中,您应该将其存储在'unsigned int'数组中。 – user1336087 2014-10-28 18:10:28