如何把一个十六进制字符串到一个无符号的字符数组? [英] How to turn a hex string into an unsigned char array?

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

问题描述

例如,我有一个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 used 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天全站免登陆