将十六进制转换为二进制

时间:2014-10-28 17:45:05

标签: c

我试图找出为什么这段代码只采用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;
}

1 个答案:

答案 0 :(得分:0)

您需要使用数组来存储二进制数,因为int变量无法存储大数字,int的范围(通常)来自{ {1}}到−32767C data types.

例如:


+32767

<强>输出

#include <stdio.h>
#include <math.h>

int hex_binary(char hex[], int binary_number[]);

int main()
{
    char hex[20];
    int binary_number[100];
    int j,k;

    printf("Enter hexadecimal number: ");
    scanf("%19s",hex);
    j = hex_binary(hex,binary_number);

    printf("Binary number is: ");
    for(k=j-1;k>=0;k--)
        printf("%d",binary_number[k]);
    printf("\n");

    return 0;
}

//Function to convert hexadecimal to binary.

int hex_binary(char hex[], int binary_number[])   
{
    int i, j=0, length, decimal=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. 
    while (decimal!=0)
    {
        binary_number[j++] = decimal%2;
        decimal/=2;
    }
    return j;
}