user3613664
user3613664

Reputation: 53

Convert to ascii to hex without using print

So I want to be able to somehow change a string into hex like so: "ab.c2" --> "61622e6332". All the help I've found online shows how to do it by using print, but I don't want to use print because it doesn't store the hex value.

What I know so far is that if you take a char and cast it to an int you get the ascii value and with that I can get the hex, which is where I'm stumped.

Upvotes: 0

Views: 756

Answers (1)

paxdiablo
paxdiablo

Reputation: 881283

Here's one way to do it, a complete program but the "meat" is in the tohex function:

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

char * tohex (unsigned char *s) {
    size_t i, len = strlen (s) * 2;

    // Allocate buffer for hex string result.
    // Only output if allocation worked.

    char *buff = malloc (len + 1);
    if (buff != NULL) {
        // Each char converted to hex digit string
        // and put in correct place.

        for (i = 0; i < len ; i += 2) {
            sprintf (&(buff[i]), "%02x", *s++);
        }
    }

    // Return allocated string (or NULL on failure).

    return buff;
}

int main (void) {
    char *input = "ab.c2";

    char *hexbit = tohex (input);
    printf ("[%s] -> [%s]\n", input, hexbit);
    free (hexbit);

    return 0;
}

There are of course other ways to achieve the same result, such as avoiding memory allocation if you can ensure you provide your own buffer that's big enough, something like:

#include <stdio.h>

void tohex (unsigned char *in, char *out) {
    while (*in != '\0') {
        sprintf (out, "%02x", *in++);
        out += 2;
    }
}

int main (void) {
    char input[] = "ab.c2";
    char output[sizeof(input) * 2 - 1];
    tohex (input, output);
    printf ("[%s] -> [%s]\n", input, output);
    return 0;
}

Upvotes: 2

Related Questions