在C中以十六进制打印字符数组
我有一个名为在C中以十六进制打印字符数组,c,arrays,hex,converter,base,C,Arrays,Hex,Converter,Base,我有一个名为char**str(由malloc分配)的2D数组。假设str[0]具有字符串“hello”。我怎么打印那个十六进制 我尝试了printf(“%d\n”),(unsigned char)strtol(str[0],NULL,16)),但没有用十六进制打印出来 任何帮助都将不胜感激,谢谢 使用%x标志打印十六进制整数 示例.c #include <stdio.h> #include <stdlib.h> #include <string.h> in
char**str
(由malloc分配)的2D数组。假设str[0]具有字符串“hello”。我怎么打印那个十六进制
我尝试了printf(“%d\n”),(unsigned char)strtol(str[0],NULL,16))
,但没有用十六进制打印出来
任何帮助都将不胜感激,谢谢
使用%x标志打印十六进制整数
示例.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;
}
参考
- 您对
strtol
的功能感到困惑。如果您有一个以十六进制表示数字的字符串,您可以像使用以下命令一样使用strtol
:
char s[] = "ff2d";
int n = strtol(s, NULL, 16);
printf("Number: %d\n", n);
尝试以十六进制打印字符串的字符时,请为字符串的每个字符使用%x
格式说明符
char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
printf("%02x", *cp);
}
可能重复的谢谢!但是2在
%2x
中做什么呢?如果我把它取出来,它仍然打印相同的十六进制。这意味着使用2的宽度来打印数字。它应该是%02x
,这样如果数字小于16,它就会打印一个前导零。谢谢!这些链接真的很有帮助,而且总是很高兴看到不同的方法来做同样的事情。同样,上面的问题02在%02x
%02中做了什么?02只是零填充,因此如果十六进制整数长度小于2字节,例如9,那么它将打印09。。alpha字符不是必需的,因为它们都在两字节的十六进制范围内。你能解释一下光标吗?此外,除非将*string
更改为string[]
,否则这将导致编译器错误。
char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
printf("%02x", *cp);
}