我試圖弄清楚爲什麼這個代碼只用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