Convert Ascii number to Hex in C

Learn convert ascii number to hex in c with practical examples, diagrams, and best practices. Covers c++, c, embedded development techniques with visual explanations.

Converting ASCII Numbers to Hexadecimal in C/C++

Hero image for Convert Ascii number to Hex in C

Learn how to convert ASCII character representations of numbers into their hexadecimal string equivalents in C and C++ for embedded systems and general programming.

In programming, especially in embedded systems or when dealing with data protocols, you often encounter scenarios where you need to convert a numeric value represented as an ASCII character (e.g., the character '5') into its hexadecimal string equivalent (e.g., "0x35" or "35"). This article explores various methods to achieve this in C and C++, focusing on clarity and efficiency.

Understanding ASCII and Hexadecimal

ASCII (American Standard Code for Information Interchange) assigns unique numerical values to characters. For example, the character '0' has an ASCII value of 48 (decimal), '1' is 49, and so on. Hexadecimal (base-16) is a number system that uses 16 distinct symbols, typically 0-9 and A-F, to represent values. Each hexadecimal digit corresponds to four binary digits (bits). When we talk about converting an 'ASCII number to hex', we usually mean converting the ASCII value of a digit character into its two-character hexadecimal string representation.

flowchart TD
    A[Input: ASCII Character '5'] --> B{Get ASCII Value}
    B --> C[ASCII Value: 53 (decimal)]
    C --> D{Convert Decimal to Hex String}
    D --> E[Output: Hex String "35"]

Conceptual flow for converting an ASCII digit character to its hexadecimal string representation.

Method 1: Using sprintf for Direct Conversion

The sprintf function (or snprintf for safer buffer handling) is a versatile tool for formatting strings. You can use it to directly convert an integer (which an ASCII character implicitly is) into its hexadecimal string representation. This is often the simplest and most readable approach for single character conversions.

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

void asciiToHexSprintf(char ascii_char, char* hex_str) {
    // The character 'ascii_char' is implicitly converted to its ASCII integer value.
    // %02X formats the integer as a two-digit uppercase hexadecimal number.
    sprintf(hex_str, "%02X", (unsigned char)ascii_char);
}

int main() {
    char my_char = 'A'; // ASCII value 65 (decimal)
    char hex_buffer[3]; // 2 chars for hex + 1 for null terminator

    asciiToHexSprintf(my_char, hex_buffer);
    printf("ASCII '%c' (decimal %d) -> Hex: %s\n", my_char, my_char, hex_buffer);

    my_char = '5'; // ASCII value 53 (decimal)
    asciiToHexSprintf(my_char, hex_buffer);
    printf("ASCII '%c' (decimal %d) -> Hex: %s\n", my_char, my_char, hex_buffer);

    my_char = 255; // Example for a non-printable character (0xFF)
    asciiToHexSprintf(my_char, hex_buffer);
    printf("ASCII '%c' (decimal %d) -> Hex: %s\n", my_char, my_char, hex_buffer);

    return 0;
}

Converting an ASCII character to a two-digit hexadecimal string using sprintf.

Method 2: Manual Bitwise Operations and Lookup

For performance-critical applications or environments where sprintf might be too heavy (e.g., very constrained embedded systems), you can implement the conversion manually using bitwise operations and a lookup table. This method gives you fine-grained control and can be more efficient for converting many characters.

#include <stdio.h>

// Lookup table for hexadecimal digits
const char hex_digits[] = "0123456789ABCDEF";

void asciiToHexManual(char ascii_char, char* hex_str) {
    unsigned char val = (unsigned char)ascii_char;

    // Get the upper 4 bits (first hex digit)
    hex_str[0] = hex_digits[(val >> 4) & 0x0F];

    // Get the lower 4 bits (second hex digit)
    hex_str[1] = hex_digits[val & 0x0F];

    hex_str[2] = '\0'; // Null-terminate the string
}

int main() {
    char my_char = 'Z'; // ASCII value 90 (decimal)
    char hex_buffer[3];

    asciiToHexManual(my_char, hex_buffer);
    printf("ASCII '%c' (decimal %d) -> Hex: %s\n", my_char, my_char, hex_buffer);

    my_char = 10; // Newline character (0x0A)
    asciiToHexManual(my_char, hex_buffer);
    printf("ASCII '%c' (decimal %d) -> Hex: %s\n", my_char, my_char, hex_buffer);

    return 0;
}

Manual conversion of an ASCII character to a two-digit hexadecimal string using bitwise operations and a lookup table.

Converting a String of ASCII Digits to a Hex String

If you have a string of ASCII characters, and you want to convert each character's ASCII value into its hexadecimal representation, you can iterate through the string and apply one of the above methods.

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

const char hex_digits[] = "0123456789ABCDEF";

void stringAsciiToHexString(const char* ascii_str, char* hex_output_buffer) {
    int len = strlen(ascii_str);
    for (int i = 0; i < len; ++i) {
        unsigned char val = (unsigned char)ascii_str[i];
        hex_output_buffer[i * 2] = hex_digits[(val >> 4) & 0x0F];
        hex_output_buffer[i * 2 + 1] = hex_digits[val & 0x0F];
    }
    hex_output_buffer[len * 2] = '\0'; // Null-terminate the final string
}

int main() {
    const char* input_string = "Hello"; // ASCII values: 72, 101, 108, 108, 111
    char output_hex_buffer[strlen(input_string) * 2 + 1]; // Each char becomes 2 hex chars + null terminator

    stringAsciiToHexString(input_string, output_hex_buffer);
    printf("Input ASCII string: \"%s\"\n", input_string);
    printf("Converted Hex string: %s\n", output_hex_buffer);

    return 0;
}

Converting an entire ASCII string to a hexadecimal string representation of its characters.

1. Determine Input Type

First, clarify if you are converting a single ASCII character or an entire string of ASCII characters. This will influence your buffer sizing and loop structure.

2. Choose Conversion Method

Decide between sprintf (simpler, more readable, generally sufficient) and manual bitwise operations (more performant, suitable for embedded or high-throughput scenarios).

3. Allocate Output Buffer

Ensure your destination character array (buffer) is large enough. For each ASCII character, you'll need two characters for its hexadecimal representation, plus one for the null terminator if you're creating a C-style string.

4. Perform Conversion

Apply the chosen method. If converting a string, iterate through the input, converting each character individually and placing the result in the correct position in the output buffer.

5. Null-Terminate (if string)

If your output is intended to be a C-style string, remember to null-terminate it (\0) at the end.