Linux C程序-十六进制如何以0x作为前缀

时间:2019-10-11 20:07:13

标签: c linux hex

该程序将字符串转换为十六进制。

#include <stdio.h>
#include <string.h>

int main(void) {
  char text[] = "thank you";
  int len = strlen(text);

  char hex[100], string[50];

  // Convert text to hex.
  int i,j;

  for ( i = 0, j = 0; i < len; i++, j+= 2) {
    sprintf(hex + j, "%02X", text[i] );
    printf("0x%X ", text[i] ); //this prints fine
    }
  printf("'%s' in hex is %s.\n", text, hex); //'thank you' in hex is 7468616e6b20796f75.

  // Convert the hex back to a string.
  len = strlen(hex);
  for (i = 0, j = 0; j < len; i++, j+= 2) {
    int val[1];
    sscanf(hex + j, "%2x", val);
    string[i] = val[0];
    string[i + 1] = '\0';
  }

  printf("%s as a string is '%s'.\n", hex, string);

  return 0;
}

但是我需要0x74, 0x68, 0x61, 0x6E, 0x6B, 0x20, 0x79, 0x6F, 0x75 或分配给数组

无符号字符键[] = {0x74、0x68、0x61、0x6E,0x6B,0x20、0x79、0x6F,0x75};

如何将十六进制值存储到字符串中。

1 个答案:

答案 0 :(得分:2)

使用0x格式的sprintf(),并增加增加的数量j

for ( i = 0, j = 0; i < len; i++, j+= 5) {
    sprintf(hex + j, "0x%02X ", text[i] );
    printf("0x%X ", text[i] );
}

然后,在扫描时需要允许它。跳过前两个字符,然后增加5

也不需要建立val数组,只需要一个int变量。而且,您可以在循环末尾添加空终止符,而不是每次循环都添加。

for (i = 0, j = 2; j < len; i++, j+= 5) {
    int val;
    sscanf(hex + j, "%2x", &val);
    string[i] = val;
}
string[i + 1] = '\0';

DEMO