在C中将字符数组打印为十六进制

neb*_*eby 1 c arrays hex converter base

我有一个称为char **str(由malloc分配)的2D数组。假设str [0]具有字符串“ hello”。我将如何打印该十六进制?

我试过了printf("%d\n", (unsigned char)strtol(str[0], NULL, 16)),但这并不能以十六进制形式打印出来。

任何帮助,将不胜感激,谢谢!

amd*_*xon 5

使用%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)

参考


R S*_*ahu 5

您对的功能感到困惑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)