How to convert hexadecimal number to binary in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>
#include <string.h>

const char *hex_char_to_binary(char ch) {
    switch (toupper(ch)) {
        case '0': return "0000";
        case '1': return "0001";
        case '2': return "0010";
        case '3': return "0011";
        case '4': return "0100";
        case '5': return "0101";
        case '6': return "0110";
        case '7': return "0111";
        case '8': return "1000";
        case '9': return "1001";
        case 'A': return "1010";
        case 'B': return "1011";
        case 'C': return "1100";
        case 'D': return "1101";
        case 'E': return "1110";
        case 'F': return "1111";
    }
    return "";
}
 
char *hex_to_binary(char *hex, int size, char *binary) {
    for (int i = 0; i != size; i++)
       strcpy(binary + i * 4, hex_char_to_binary(hex[i]));
        
    return binary;
} 
 
int main() {
    char hex[8] = "1BC", binary[32]; 
   
    printf("%s", hex_to_binary(hex, 8, binary)); 
}
 
 
/*
run:
 
000110111100
 
*/

 



answered Apr 1, 2019 by avibootz

Related questions

1 answer 138 views
138 views asked Sep 17, 2021 by avibootz
1 answer 138 views
138 views asked Aug 24, 2021 by avibootz
1 answer 144 views
1 answer 212 views
1 answer 131 views
131 views asked Sep 17, 2021 by avibootz
1 answer 128 views
128 views asked Aug 24, 2021 by avibootz
...