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:
#include <stdio.h>
: Includes the standard input/output library for functions likeprintf
.#include <string.h>
: Includes the string manipulation library for functions likestrlen
.void textToHex(const char text)
: Defines a function namedtextToHex
that takes a string (const char text
) as input and returnsvoid
(no return value).int len = strlen(text);
: Calculates the length of the input text using thestrlen
function.printf("Text: %s\n", text);
: Prints the original text.printf("Hex: ");
: Prints the label for the hexadecimal representation.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.printf("\n");
: Prints a newline character to format the output.int main() { ... }
: Defines the main function, the entry point of the program.const char *inputText = "Hello, World!";
: Initializes a string with the text "Hello, World!".textToHex(inputText);
: Calls thetextToHex
function with the input text as an argument.return 0;
: Indicates successful program execution.