将十六进制字符串转换为字节数组

新手上路,请多包涵

将可变长度十六进制字符串(例如 "01A1" )转换为包含该数据的字节数组的最佳方法是什么。

即转换这个:

 std::string = "01A1";

进入这个

char* hexArray;
int hexLength;

或这个

std::vector<char> hexArray;

这样当我将其写入文件和 hexdump -C 时,我会得到包含 01A1 的二进制数据。

原文由 oracal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

这应该有效:

 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;
  }
}

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

原文由 Niels Keurentjes 发布,翻译遵循 CC BY-SA 3.0 许可协议

static bool Hexadec2xdigit(const std::string& data, std::string& buffer, std::size_t offset = sizeof(uint16_t))
{
    if (data.empty())
    {
        return false;
    }

    try
    {
        constexpr auto s_function_lambda = [] (const char* string) noexcept { return *static_cast<const uint16_t*>(reinterpret_cast<const uint16_t*>(string)); };
        {
            for (std::size_t i = 0, tmp = s_function_lambda(data.c_str() + i); i < data.size(); i += offset, tmp = s_function_lambda(data.c_str() + i))
            {
                if (std::isxdigit(data[i]))
                {
                    buffer += static_cast<char>(/*std::stoul*/std::strtoul(reinterpret_cast<const char*>(std::addressof(tmp)), NULL, 16));
                }
            }
        }

        return true;
    }
    catch (const std::invalid_argument& ex)
    {

    }
    catch (const std::out_of_range& ex)
    {

    }

    return false;
}

  • 这段代码没有太多的复制过程

原文由 Zephyr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题