Chuyển chuỗi ký tự sang biểu diễn hexadecimal ASCII tương ứng.
Chương trình C++
#include <stdio.h>
#include <string.h>
void convert_hexa(char* input, char* output) {
int loop = 0, i = 0;
while (input[loop] != '\0') {
sprintf((char*)(output + i), "%02X", input[loop]);
loop += 1;
i += 2;
}
output[i++] = '\0'; // Kết thúc chuỗi
}
int main() {
char ascii_str[] = "tutorials point";
int len = strlen(ascii_str);
char hex_str[(len * 2) + 1];
convert_hexa(ascii_str, hex_str);
printf("ASCII: %s\n", ascii_str);
printf("Hexadecimal: %s\n", hex_str);
return 0;
}
Kết quả
ASCII: tutorials point Hexadecimal: 7475746F7269616C7320706F696E74
Giải thích
- Mỗi ký tự ASCII chuyển thành 2 chữ số hex
- %02X: định dạng hex in hoa, độ rộng 2, đệm 0
- 't' = 0x74, 'u' = 0x75, 't' = 0x74, 'o' = 0x6F, 'r' = 0x72, 'i' = 0x69, 'a' = 0x61, 'l' = 0x6C, 's' = 0x73, ' ' = 0x20, 'p' = 0x70, 'o' = 0x6F, 'i' = 0x69, 'n' = 0x6E, 't' = 0x74