This blog is under construction

Friday 5 July 2013

C program to convert binary to hexadecimal

How to convert binary value to hexadecimal equivalent?
Binary Value 111100101
111100101 = 1 (1110) (0101) = (0001) (1110) (0101) = (1) (E) (5)
  • Group the binary values(4 digits in each group).
  • Find the hexadecimal value for each group and append the outputs.

Write a C program to convert binary value to hexadecimal.


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

  void binaryToHexa(char *data) {
        int i = 0, res = 0, val = 0, count = 3;
        char hexaChar[] = {'A', 'B', 'C', 'D', 'E', 'F'};

        printf("Equivalent Hexadecimal Value: 0x");
        /*
         * find hexadecimal value for every 4 digit
         * (start from MSB) and print it
         */
        while (data[i] != '\0') {
                val = val + (data[i] - '0') * pow(2, count);
                i++;
                count--;
                if (i % 4 == 0) {
                        if (val > 9) {
                                printf("%c", hexaChar[val - 10]);
                        } else {
                                printf("%d", val);
                        }
                        val = 0, count = 3;
                }
        }
        printf("\n");
  }

  int main() {
        char input[100], temp[512], ch;
        int value = 0, power = 0, i = 0, j = 0, res, len;

        /* get the binary value from the user */
        printf("Enter your binary value:");
        fgets(input, 100, stdin);
        input[strlen(input) - 1] = '\0';

        len = strlen(input);
        /* 
         * doing 4 digit alignment for the above obtained binary
         * input.  For example, if the binary input is 1, make
         * it four digit aligned.  0001
         */
        if (len % 4 != 0) {
                for (i = len; i >= 0; i--) {
                        input[i + (4 - (len % 4))] = input[i];
                }
                len = 4 - (len % 4);
                while (len > 0) {
                        input[len - 1] = '0';
                        len--;
                }
        }
        /* converting binary value to hexadecimal value */
        binaryToHexa(input);
        return 0;
  }


Note:
gcc binToHexa.c -lm => linked match library since we have used pow() function.

  Output:
jp@jp-VirtualBox:~/$ gcc binToHexa.c -lm
jp@jp-VirtualBox:~/$ ./a.out
Enter your binary value:111101100
Equivalent Hexadecimal Value: 0x1EC



No comments:

Post a Comment