Hex String to char * array C ++

时间:2015-02-13 14:01:28

标签: c++ string hex

我使用此代码将char *转换为十六进制字符串

char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F' };

      std::string hex_str;
      for (int i = 0; i < byte_received; ++i)
      {
        const char ch = data[i];
        hex_str.append(&hex[(ch  & 0xF0) >> 4], 1);
        hex_str.append(&hex[ch & 0xF], 1);
      }

如何从十六进制字符串到原始数据进行反向转换?

1 个答案:

答案 0 :(得分:0)

我认为这将为您输入十六进制字符串的char数组输出。

#include <iostream>
#include <algorithm>

using namespace std;


char* hextostr(const std::string& hexStr)
{
    const char* const hex = "0123456789ABCDEF";
    size_t len = hexStr.length();
    int k=0;
    if (len & 1) return NULL;

    char* output = new char[(len/2)+1];
    for (size_t i = 0; i < len; i += 2)
    {
        char a,b;

        a = hexStr[i];
        const char* p = std::lower_bound(hex, hex + 16, a);
        if (*p != a) return NULL;

        b = hexStr[i + 1];
        const char* q = std::lower_bound(hex, hex + 16, b);
        if (*q != b) return NULL;

        output[k++] = ((p - hex) << 4) | (q - hex);
    }
    output[k] = '\0';
    return output;
}

或者你也可以这样做

char* hextostr(const std::string& hexStr)
{
    size_t len = hexStr.length();
    int k=0;
    if (len & 1) return NULL;

    char* output = new char[(len/2)+1];
    for (size_t i = 0; i < len; i+=2)
    {
        output[k++] = (((hexStr[i] >= 'A')? (hexStr[i] - 'A' + 10): (hexStr[i] - '0')) << 4) |
                      (((hexStr[i+1] >= 'A')? (hexStr[i+1] - 'A' + 10): (hexStr[i+1] - '0')));
    }
    output[k] = '\0';
    return output;
}