Introduction
The code presented here is used to convert a stream of hex values coming from the network to the corresponding ASCII values. Each 4 bits of a hex value is coming in its corresponding 8 bit format in the stream.
Background
We were working on a project in which we were getting a stream of data that was actually a Hex stream. Now every character in the stream was actually representing only 4 bits of the actual hex value. So 2 characters were required to form the actual hex value. I had checked the internet for a quick solution but was not very happy with what I saw. So I decided to write on of my own. I would not say this is the best solution. But it is fast enough.
Using the code
The code can be used by passing the character array arr to the function hexToAscii(). Here, the 2 different characters are actually 2 nibbles of a hex value. so 606162 are actually decoded as 0x60, 0x61, 0x62 and so on. The result is stored in an integer array destElements.
srcElements is the size of the array being passed as the input parameter (here arr).
unsigned char arr[] = {"606162636465666768696a6b6c6d6e6f\
707172737475767778797a7b7c7d7e7f8081828384858687"};
char *hexToAscii (char *srcHex, int *destElements, int srcElements)
{
int index, destIndex;
unsigned char valUpper, valLower, *ascArray;
int lowerFlag;
lowerFlag = 0;
ascArray = NULL;
*destElements = srcElements/2;
ascArray = (char *)malloc (*destElements);
if (ascArray == NULL) {
return NULL;
}
for (destIndex = 0; destIndex < *destElements; destIndex++) {
for (index = 0; index < 2; index++) {
if (lowerFlag == 0) {
if (srcHex[(destIndex * 2) + index] >= '0' &&
srcHex[(destIndex * 2) + index] <= '9') {
valUpper = srcHex[(destIndex * 2) + index] - '0';
} else if (tolower (srcHex[(destIndex * 2) + index]) >= 'a' ||
tolower (srcHex[(destIndex * 2) + index]) <= 'f'){
valUpper = tolower(srcHex[(destIndex * 2) + index]) - 'a' + 10;
}
valUpper <<= 4;
lowerFlag = 1;
} else {
if (srcHex[(destIndex * 2) + index] >= '0' &&
srcHex[(destIndex * 2) + index] <= '9') {
valLower = srcHex[(destIndex * 2) + index] - '0';
} else if (tolower (srcHex[(destIndex * 2) + index]) >= 'a' ||
tolower (srcHex[(destIndex * 2) + index]) <= 'f'){
valLower = tolower (srcHex[(destIndex * 2) + index]) - 'a' + 10;
}
lowerFlag = 0;
}
}
ascArray[destIndex] = valUpper | valLower;
}
return ascArray;
}
Points of Interest
It was just fun coding this :-).
History
N/A