C Program to Convert Characters to Hex C Source Text


Given a text string, we want to convert to their Hexadecimal representations. The following C program when compiled and run, takes the command line parameters, convert to ASCII code and then print the Hex string to console.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <string.h>
 
void hex(unsigned char a, char* buf) {
    // hex lookup table
    char data[] = "0123456789ABCDEF";
    buf[0] = '0';
    buf[1] = 'x';
    int i = 2;
    while (a) {
        buf[i ++] = data[a % 16];
        a /= 16;
    }    
    int j = 2;
    -- i;
    // reverse i..j
    while (j < i) {
        char t = buf[j];
        buf[j] = buf[i];
        buf[i] = t;
        i --;
        j ++;
    }
}
 
int main(int argc, char* argv[]) {
    if (argc == 0) {
        return 0;
    }
    for (int i = 1; i < argc; ++ i) {
        for (int j = 0; j < strlen(argv[i]); ++ j) {
            char buf[4];
            unsigned char cur = argv[i][j] & 0xFF;
            hex(cur, buf);
            printf("\"%s\", ", buf);
        }
    }
    printf("\n");
    return 0;
}
#include <stdio.h>
#include <string.h>

void hex(unsigned char a, char* buf) {
    // hex lookup table
    char data[] = "0123456789ABCDEF";
    buf[0] = '0';
    buf[1] = 'x';
    int i = 2;
    while (a) {
        buf[i ++] = data[a % 16];
        a /= 16;
    }    
    int j = 2;
    -- i;
    // reverse i..j
    while (j < i) {
        char t = buf[j];
        buf[j] = buf[i];
        buf[i] = t;
        i --;
        j ++;
    }
}

int main(int argc, char* argv[]) {
    if (argc == 0) {
        return 0;
    }
    for (int i = 1; i < argc; ++ i) {
        for (int j = 0; j < strlen(argv[i]); ++ j) {
            char buf[4];
            unsigned char cur = argv[i][j] & 0xFF;
            hex(cur, buf);
            printf("\"%s\", ", buf);
        }
    }
    printf("\n");
    return 0;
}

Compile using gcc hex.c -o hex

1
2
# ./hex Hello
"0x48", "0x65", "0x6C", "0x6C", "0x6F", 
# ./hex Hello
"0x48", "0x65", "0x6C", "0x6C", "0x6F", 

Online tool to convert String-Text to ASCII.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
244 words
Last Post: Teaching Kids Programming - Redistribute Characters to Make All Strings Equal
Next Post: Teaching Kids Programming - Length of Longest Balanced Subsequence

The Permanent URL is: C Program to Convert Characters to Hex C Source Text

Leave a Reply