To "save" the result, simple add a buffer, dest
, to store the result.
Additional suggestions included in code.
// add void to signature
int main(void) {
const char st[12] = "48656C6C6F3B";
int length = strlen(st);
int i;
char buf = 0;
// add destination buffer
char dest[10];
// Add test
// for (i = 0; i < length; i++) {
for (i = 0; i < length && (i/2 + 1) < sizeof(dest); i++) {
if (i % 2 != 0) {
// printf("%c", hex_to_ascii(buf, st[i]));
dest[i/2] = hex_to_ascii(buf, st[i]);
} else {
buf = st[i];
}
}
// Add termination
dest[i/2] = '\0';
// Do someting with dest
puts(dest);
return 0;
}
Alternatively, some code that handles various possible issues: lower/upper case hex digits, invalid characters, odd count, small buffer, embedded null character.
#include <stdlib.h>
#include <string.h>
// There are _many_ ways to do this step.
unsigned char2digit(int ch) {
static const char Hex[] = "0123456789ABCDEF0123456789abcdef";
char *p = memchr(Hex, ch, 32);
if (p) {
return (unsigned) (p - Hex) % 16;
}
return (unsigned) -1; // error value
}
// Return NULL with ill-formed string
char *HexStringToString(char *dest, size_t size, const char *src) {
char *p = dest;
if (size <= 0) {
return NULL;
}
size--;
while (*src) {
if (size == 0) return NULL;
size--;
unsigned msb = char2digit(*src++);
if (msb > 15) return NULL;
unsigned lsb = char2digit(*src++);
if (lsb > 15) return NULL;
char ch = (char) (msb * 16 + lsb);
// Optionally test for embedded null character
if (ch == 0) return NULL;
*p++ = ch;
}
*p = '\0';
return dest;
}
void testHex(const char *s) {
char buf[10];
char *dest = HexStringToString(buf, sizeof buf, s);
printf("%-24s --> '%s'\n", s, dest ? dest : "NULL");
}
#include <stdio.h>
int main(void) {
testHex("48656C6C6F3B"); // upper case
testHex("48656c6c6f3b"); // lower case
testHex("");
testHex("48656C6C6F3B48656C");
// fails
testHex("48656C6C6F3B48656C6C"); // Too long
testHex("48656C6C6F3B0"); // Odd character count
testHex("48656C6C6F3Bxx"); // Non-hex character
testHex("48006C6C6F3B"); // null character
return 0;
}
Output
48656C6C6F3B --> 'Hello;'
48656c6c6f3b --> 'Hello;'
--> ''
48656C6C6F3B48656C --> 'Hello;Hel'
48656C6C6F3B48656C6C --> 'NULL'
48656C6C6F3B0 --> 'NULL'
48656C6C6F3Bxx --> 'NULL'
48006C6C6F3B --> 'NULL'