From Text to Hex

In last week’s Lesson, I showed a program that translates a string of hex values into ASCII text. This code was to sate the nerd in me so that when another nerd writes 48 65 6c 6c 6f 2c 20 66 65 6c 6c 6f 77 20 6e 65 72 64 21, I can respond accordingly. But to respond in hex, a second program is required, one that translates ASCII text into a string of hex values.

As with the hex-to-ascii example, writing code that gobbles a string of text and spits out hexadecimal values isn’t really that complex: You ask for input, print each character in the string as a hex value, and you’re done. Here is such code:

#include <stdio.h>

#define SIZE 32

int main()
{
    char string[SIZE];
    int i = 0;

    printf("Text to translate: ");
    fgets(string,SIZE,stdin);
    while(string[i] != '\n')
    {
        printf("%2x ",string[i]);
        i++;
    }
    putchar(string[i]);

    return(0);
}

Lines 10 and 11 prompt for input. I chose to use the fgets() function in Line 11, which helps check the size of the input buffer, string[].

Line 12 starts a while loop to process the input buffer. The %2x format for output, which displays each character value as a 2-digit, lower case, hex number. The loop continues until the newline ('\n') is found, which is when fgets() stops reading input.

Because i still references the newline in the string[] array, Line 17 prints that character, which makes for clean output.

Here’s a sample run:

Text to translate: Oh my goodness!
4f 68 20 6d 79 20 67 6f 6f 64 6e 65 73 73 21

You can take those values and plug them into the program from last week’s Lesson to translate back the text:

Type hex (l/c) digits, 0 to end: 4f 68 20 6d 79 20 67 6f 6f 64 6e 65 73 73 21 0

Oh my goodness!

And the nerd in me is quite content, thank you.

Leave a Reply