Tuesday, May 19, 2015

Hex to Binary in C programming with different Methods


Method 1:::::

/* Written by Prakash Katudia
   Compile it with below command
   "gcc -lm hexToDec.c"
*/


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

int main(){

    char str[10],ch;
    int a[255], b[256],len,i,k,j=0,num,rem=0,dec=0;
    printf("Enter hex number\n");
    scanf("%s",str);
    len = strlen(str);
    for(i=len-1;i>=0;i--)
    {
    /* take a case for A,B,C,D,E,F hex num */
    ch=str[i],k=0;
    switch(ch)
    {
        case 'A':
        num = 10;
        break;
        case 'B':
        num = 11;
        break;
        case 'C':
        num = 12;
        break;
        case 'D':
        num = 13;
        break;
        case 'E':
        num = 14;
        break;
        case 'F':
        num = 15;
        break;
        default :
        num = str[i] - '0';
        }
    /* store in array in binary */
    while(k<=3){
        if(num!=0){
            rem = num%2;
        a[j] = rem;
        num = num/2;
        }
        else
        a[j] = 0;
        j++;k++;
        }
   
    }
    printf("Binary of given hex code is= ");
    /* print binary and convert it into decimal as well */
    for(i=j-1;i>=0;i--)
    {
        printf("%d",a[i]);
        dec = dec + (a[i]*pow(2,i));

    }
    printf("\nDecimal of given hex is = %d \n",dec);
   
 return 0;

}



Method 2:

#include <stdio.h>
int main()
{
    char s[] = "FF";
    int x;
    sscanf(s, "%x", &x);
    printf("%u\n", x);
    return 0;
}