1

我一直在尝试执行从包含十六进制字符串的 CString 到字节数组的转换,并且一直

到目前为止不成功。我看过论坛,到目前为止似乎都没有帮助。有没有只有几个的功能

执行此转换的代码行?

我的代码:

BYTE abyData[8];    // BYTE = unsigned char

CString sByte = "0E00000000000400";

期待:

abyData[0] = 0x0E;
abyData[6] = 0x04; // etc.
4

3 回答 3

3

您可以一次简单地吞噬两个字符:

unsigned int value(char c)
{
    if (c >= '0' && c <= '9') { return c - '0'; }
    if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
    if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }

    return -1; // Error!
}

for (unsigned int i = 0; i != 8; ++i)
{
    abyData[i] = value(sByte[2 * i]) * 16 + value(sByte[2 * i + 1]);
}

当然8应该是你的数组的大小,并且你应该确保字符串的长度正好是原来的两倍。对此的检查版本将确保每个字符都是有效的十六进制数字,如果不是这种情况,则会发出某种类型的错误信号。

于 2012-09-19T11:35:54.553 回答
2

像这样的东西怎么样:

for (int i = 0; i < sizeof(abyData) && (i * 2) < sByte.GetLength(); i++)
{
    char ch1 = sByte[i * 2];
    char ch2 = sByte[i * 2 + 1];

    int value = 0;

    if (std::isdigit(ch1))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    // That was the four high bits, so make them that
    value <<= 4;

    if (std::isdigit(ch2))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    abyData[i] = value;
}

注意:以上代码未经测试。

于 2012-09-19T11:32:48.873 回答
1

你可以:

#include <stdint.h>
#include <sstream>
#include <iostream>

int main() {
    unsigned char result[8];
    std::stringstream ss;
    ss << std::hex << "0E00000000000400";
    ss >> *( reinterpret_cast<uint64_t *>( result ) );
    std::cout << static_cast<int>( result[1] ) << std::endl;
}

但是请注意内存管理问题!另外,结果与您期望的相反,因此:

result[0] = 0x00
result[1] = 0x04
...
result[7] = 0x0E
于 2012-09-19T12:14:58.007 回答