6 - Bit Patterns
Write a function called hexToBinary that returns a character pointer to an array that represents the (unsigned) binary equivalent of the function's single character array parameter. Your function should return the NULL pointer if it is passed and invalid string, i.e. one that contains characters are not hexadecimal digits (0 to 9 and a to f). You are not required to deal with negative hexadecimal numbers.
Creating a Bit String
Your function must use malloc or calloc to create an array in dynamic memory, and return a pointer to this array. Therefore, when you use this function you must assign its result to a character pointer.
The function should generate a string of '1's and '0's that represents the binary equivalent of a hexadecimal value. Since this is a string representation the string must be terminated by a null character. The function's only parameter should be a string (character array) representation of a hexadecimal number: that is, a string of the digits 0 to 9, and letters a to f.
Examples
§
Code:
printf("%s", hexToBinary("123e"));
should print 0001001000111110
§
Code:
printf("%s", hexToBinary("01"));
should print 00000001
§
Code:
printf("%s", hexToBinary("affe3"));
should print 10101111111111100011
Code:
const int MAX_WORD = 10;
const int ROW = 3;
const int COLUMN = 4;
const int SS1 = 4;
const int SS2 = 1;
const int SORTED1 = 8;
const int SORTED2 = 1;
const int SORTED3 = 5;
// Function prototypes go here
int main(){
// Hexadecimal to Binary Tests-------------------------
char hex[MAX_WORD];
printf("\n\nhex to binary test 1: enter a hex string\n");
scanf("%s",hex);
printf("%s = %s\n", hex, (hexToBinary(hex) ? hexToBinary(hex) : "error"));
printf("\nhex to binary test 2: enter a hex string\n");
scanf("%s",hex);
printf("%s = %s\n", hex, (hexToBinary(hex) ? hexToBinary(hex) : "error"));
printf("\nhex to binary test 3: enter a hex string\n");
scanf("%s",hex);
printf("%s = %s\n", hex, (hexToBinary(hex) ? hexToBinary(hex) : "error"));
printf("\nhex to binary test 4: enter a hex string\n");
scanf("%s",hex);
printf("%s = %s\n", hex, (hexToBinary(hex) ? hexToBinary(hex) : "error"));
return 0;
}