Hexadecimal To ASCII
This algorithm converts hexadecimal numbers to ASCII code.
/*****Please include following header files*****/
// math.h
/***********************************************/
char* GetSubString(char* str, int index, int count) {
int strLen = strlen(str);
int lastIndex = index + count;
if (index >= 0 && lastIndex > strLen) return "";
char* subStr = malloc(count + 1);
for (int i = 0; i < count; i++) {
subStr[i] = str[index + i];
}
subStr[count] = '\0';
return subStr;
}
char* AppendString(const char* str1, const char* str2) {
int str1Len = strlen(str1);
int str2Len = strlen(str2);
int strLen = str1Len + str2Len + 1;
char* str = malloc(strLen);
for (int i = 0; i < str1Len; i++)
str[i] = str1[i];
for (int i = 0; i < str2Len; i++)
str[(str1Len + i)] = str2[i];
str[strLen - 1] = '\0';
return str;
}
char* CharToString(char c) {
char* str = malloc(2);
str[0] = c;
str[1] = '\0';
return str;
}
static int HexadecimalToDecimal(char* hex)
{
int hexLength = strlen(hex);
double dec = 0;
for (int i = 0; i < hexLength; ++i)
{
char b = hex[i];
if (b >= 48 && b <= 57)
b -= 48;
else if (b >= 65 && b <= 70)
b -= 55;
dec += b * pow(16, ((hexLength - i) - 1));
}
return (int)dec;
}
char* HexadecimalToASCII(char* hex) {
char* ascii = "";
int hexLen = strlen(hex);
for (int i = 0; i < hexLen; i += 2)
{
ascii = AppendString(ascii, CharToString((char)HexadecimalToDecimal(GetSubString(hex, i, 2))));
}
return ascii;
}
Example
char* data = "50726F6772616D6D696E6720416C676F726974686D73";
char* value = HexadecimalToASCII(data);
Output
Programming Algorithms