text to hex in C

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

void textToHex(const char *text) {
    int len = strlen(text);

    printf("Text: %s\n", text);
    printf("Hex: ");

    for (int i = 0; i < len; i++) {
        printf("%02X ", (unsigned char)text[i]);
    }

    printf("\n");
}

int main() {
    const char *inputText = "Hello, World!";
    textToHex(inputText);

    return 0;
}

Explanation:

  1. #include <stdio.h>: Includes the standard input/output library for functions like printf.

  2. #include <string.h>: Includes the string manipulation library for functions like strlen.

  3. void textToHex(const char text): Defines a function named textToHex that takes a string (const char text) as input and returns void (no return value).

  4. int len = strlen(text);: Calculates the length of the input text using the strlen function.

  5. printf("Text: %s\n", text);: Prints the original text.

  6. printf("Hex: ");: Prints the label for the hexadecimal representation.

  7. for (int i = 0; i < len; i++) { printf("%02X ", (unsigned char)text[i]); }: Loops through each character in the input text and prints its hexadecimal representation using the %02X format specifier. The (unsigned char) typecast is used to ensure correct interpretation of the character's binary value.

  8. printf("\n");: Prints a newline character to format the output.

  9. int main() { ... }: Defines the main function, the entry point of the program.

  10. const char *inputText = "Hello, World!";: Initializes a string with the text "Hello, World!".

  11. textToHex(inputText);: Calls the textToHex function with the input text as an argument.

  12. return 0;: Indicates successful program execution.