How to convert from Hexadecimal to binary

Asked

Viewed 1,029 times

0

Good actually I got in brute force wanted to know, there is another way to do my code mathematically

#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
  char numero[1000],aux[10000];
  scanf("%s", numero);
  for(int i = 0; i < numero[i] && numero[i] != '\0'; i++)
  {
    if(numero[i] == '0')
    {
        strcat(aux,"0000");
    }
    else if(numero[i] == '1')
    {
        strcat(aux,"0001");
    }
    else if(numero[i] == '2')
    {
        strcat(aux,"0010");
    }
    else if(numero[i] == '3')
    {
        strcat(aux,"0011");
    }
    else if(numero[i] == '4')
    {
        strcat(aux,"0100");
    }
    else if(numero[i] == '5')
    {
        strcat(aux,"0101");
    }
    else if(numero[i] == '6')
    {
        strcat(aux,"0110");
    }
    else if(numero[i] == '7')
    {
        strcat(aux,"0111");
    }
    else if(numero[i] == '8')
    {
        strcat(aux,"1000");
    }
    else if(numero[i] == '9')
    {
        strcat(aux,"1001");
    }
    else if((numero[i] == 'A')||(numero[i])=='a')
    {
        strcat(aux,"1010");
    }
    else if((numero[i] == 'B')||(numero[i])=='b')
    {
        strcat(aux,"1011");
    }
    else if((numero[i] == 'C')||(numero[i])=='c')
    {
        strcat(aux,"1100");
    }
    else if((numero[i] == 'D')||(numero[i])=='d')
    {
        strcat(aux,"1101");
    }
    else if((numero[i] == 'E')||(numero[i])=='e')
    {
        strcat(aux,"1110");
    }
    else if((numero[i] == 'F')||(numero[i])=='f')
    {
        strcat(aux,"1111");
    }
  }
   puts(aux);
return 0;
}
  • Forgive my ignorance, but I didn’t understand some things in your code.. why the loop is, why the arrays have so much space. In my view there are 2 problems in your code: 1 - the loop is broken if any of the numbers is different from ' 0', the ideal would not be a continue? and another problem is, instead of using Else if, use switch case.

  • You could declare a int int_var; and then use scanf('%x', &int_var), this way you can already convert from hexa directly to an integer.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.