如何将十六进制字符串转换为无符号字符数组? [英] How to turn a hex string into an unsigned char array?

查看:96
本文介绍了如何将十六进制字符串转换为无符号字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个 cstring "E8 48 D8 FF FF 8B 0D"(包括空格)需要转换成等效的无符号字符数组 {0xE8,0x48,0xD8,0xFF,0xFF,0x8B,0x0D}.有什么有效的方法可以做到这一点?谢谢!

For example, I have a cstring "E8 48 D8 FF FF 8B 0D" (including spaces) which needs to be converted into the equivalent unsigned char array {0xE8,0x48,0xD8,0xFF,0xFF,0x8B,0x0D}. What's an efficient way to do this? Thanks!

我不能使用 std 库...所以考虑这是一个 C 问题.对不起!

I can't use the std library... so consider this a C question. I'm sorry!

推荐答案

你永远不会让我相信这个操作是一个性能瓶颈.有效的方法是通过使用标准 C 库充分利用您的时间:

You'll never convince me that this operation is a performance bottleneck. The efficient way is to make good use of your time by using the standard C library:

static unsigned char gethex(const char *s, char **endptr) {
  assert(s);
  while (isspace(*s)) s++;
  assert(*s);
  return strtoul(s, endptr, 16);
}

unsigned char *convert(const char *s, int *length) {
  unsigned char *answer = malloc((strlen(s) + 1) / 3);
  unsigned char *p;
  for (p = answer; *s; p++)
    *p = gethex(s, (char **)&s);
  *length = p - answer;
  return answer;
}

编译并测试.适用于您的示例.

Compiled and tested. Works on your example.

这篇关于如何将十六进制字符串转换为无符号字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆