使用%x标志输出十六进制整数
example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *string = "hello", *cursor;
cursor = string;
printf("string: %s\nhex: ", string);
while(*cursor)
{
printf("%02x", *cursor);
++cursor;
}
printf("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出
$ ./example
string: hello
hex: 68656c6c6f
Run Code Online (Sandbox Code Playgroud)
参考
您对的功能感到困惑strtol。如果您有一个以十六进制表示数字的字符串,则可以strtol像使用以下代码一样使用:
char s[] = "ff2d";
int n = strtol(s, NULL, 16);
printf("Number: %d\n", n);
Run Code Online (Sandbox Code Playgroud)
当您尝试以十六进制打印字符串的字符时,请为字符串%x的每个字符使用格式说明符。
char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
printf("%02x", *cp);
}
Run Code Online (Sandbox Code Playgroud)