C 31 Jan 2010 23:29:24

Snippet: Convert Hex to Text

//tinodidriksen.com/uploads/code/c/hex-to-text.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char buf[] = "54657374";
    size_t len = strlen(buf);

    if (len & 1) {
        printf("Cannot take hex from odd length string.\n");
        exit(1);
    }

    char *result = (char*)malloc(len/2 + 1);
    memset(result, 0, len/2 + 1);
    for (size_t i = 0 ; i < len/2 ; ++i) {
        char tmp[3] = {buf[i*2], buf[i*2+1], 0};
        result[i] = (char)strtol(tmp, NULL, 16);
    }

    printf("%s converted to %s\n", buf, result);
    free(result);

    return 0;
}

Subscribe to the comments through RSS Feed

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image