将十六进制的 char* 转换为普通 char*?

标签 c string hex

我有这个功能:

char *ctohex(char *str){
    int i=0, len;
    len = strlen(str);
    char *final = malloc(len*2*sizeof(char)+1);
    while(len--){
         sprintf(final+i*2, "%02X", str[i]);
         i++;
    }
    return final;
}

现在我想要一个反向函数,从十六进制到普通字符,这可能吗?抱歉我的英语。没有人给我一个好的答案,也许我解释错了。

我的函数中有这样的输入: JOAO 输出是: 4A4F414F

我想将 4A4F414F 放回 JOAO

最佳答案

几乎是原始 ctohex() 的简单反转

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

char *hextoc(const char *str) {
  size_t i, j, len;
  len = strlen(str);

  // If the length is not even
  if (len % 2)
    return NULL;

  char *final = malloc(len/2 + 1);
  if (final == NULL)
    return NULL;

  j = 0;
  for (i = 0; i < len; i += 2) {
    if (!isxdigit((unsigned char) str[i])
            || !isxdigit((unsigned char) str[i+1])) {
      free(final);
      return NULL;
    }
    unsigned x;
    sscanf(&str[i], "%2X", &x);
    final[j++] = (char) x;
  }
  final[j] = '\0';
  return final;
}

int main() {
  return puts(hextoc("4A4F414F"));
  // prints JOAO
}
<小时/>

ctohex(char *str) 有问题。当str[i]为<0

// sprintf(final+i*2, "%02X", str[i]);
sprintf(final+i*2, "%02X", str[i] & 0xFF);
// or
sprintf(final+i*2, "%02hhX", str[i]);  // Current C compilers

关于将十六进制的 char* 转换为普通 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22338746/

相关文章:

c - 每当我执行代码时都会得到 "-317629566"

c - 字符串没有被比较?或者输入正确?

ios - 无法将类型 '__NSCFBoolean' (0x100b123b8) 的值转换为 'NSString' (0x100f0ab48)

c - 为什么没有标准的 memswap 函数

ruby 正则表达式 : split string with match beginning with either a newline or the start of the string?

c++ - 添加用户定义类型 C++

ios - 如何根据IOS中的时间更改十六进制颜色代码

python - 从 Python 字符串中读取字节

c - C 扩展中的 Ruby 关键字参数