将十六进制字符串转换为字节数组 [英] Converting a hex string to a byte array

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

问题描述

转换可变长度十六进制字串的最佳方法是什么? 01A1到包含该数据的字节数组。

What is the best way to convert a variable length hex string e.g. "01A1" to a byte array containing that data.

即转换为:

std::string = "01A1";

到此

char* hexArray;
int hexLength;

或此

std::vector<char> hexArray;

,所以当我写这个文件和 hexdump -C it我得到包含 01A1 的二进制数据。

so that when I write this to a file and hexdump -C it I get the binary data containing 01A1.

推荐答案

这应该工作:

int char2int(char input)
{
  if(input >= '0' && input <= '9')
    return input - '0';
  if(input >= 'A' && input <= 'F')
    return input - 'A' + 10;
  if(input >= 'a' && input <= 'f')
    return input - 'a' + 10;
  throw std::invalid_argument("Invalid input string");
}

// This function assumes src to be a zero terminated sanitized string with
// an even number of [0-9a-f] characters, and target to be sufficiently large
void hex2bin(const char* src, char* target)
{
  while(*src && src[1])
  {
    *(target++) = char2int(*src)*16 + char2int(src[1]);
    src += 2;
  }
}

根据您的特定平台,可能还有一个标准实现

Depending on your specific platform there's probably also a standard implementation though.

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

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