将 80 位十六进制数从 char 数组复制到 uint16_t 向量或数组

问题描述

假设我有一个包含 80 位十六进制数的文本文件

0xabcdef0123456789abcd

我的 C++ 程序使用 fstream 将其读取到名为 buffer 的字符数组中。 但后来我想将它存储在一个 uint16_t 数组中:

uint16_t * key = {0xabcd,0xef01,0x2345,0x6789,0xabcd}

我尝试了几种方法,但我仍然得到十进制整数,例如:

const std::size_t strLength = strlen(buffer);
std::vector<uint16_t> arr16bit((strLength / 2) + 1);

for (std::size_t i = 0; i < strLength; ++i)
{
    arr16bit[i / 2] <<= 8;
    arr16bit[i / 2] |= buffer[i];
}

产量:

arr16bit = {24930,25444,25958,12337,12851}

一定有一种简单的方法可以做到这一点,但我没有看到。

这是我根据评论提出的完整解决方案:

int hex_char_to_int(char c) {
    if (int(c) < 58) //numbers
        return c - 48;
    else if (int(c) < 91) //capital letters
        return c - 65 + 10;
    else if (int(c) < 123) //lower case letters
        return c - 97 + 10;
}
uint16_t ints_to_int16(int i0,int i1,int i2,int i3) {
    return (i3 * 16 * 16 * 16) + (i2 * 16 * 16) + (i1 * 16) + i0;
}

void readKey() {
    const int bufferSize = 25;
    char buffer[bufferSize] = { NULL };
    ifstream* pStream = new ifstream("key.txt");
    if (pStream->is_open() == true)
    {
        pStream->read(buffer,bufferSize);
    }
    cout << buffer << endl;
    const size_t strLength = strlen(buffer);
    int* hex_to_int = new int[strLength - 2];
    for (int i = 2; i < strLength; i++) {
        hex_to_int[i - 2] = hex_char_to_int(buffer[i]);
    }
    cout << endl;
    uint16_t* key16 = new uint16_t[5];
    int j = 0;
    for (int i = 0; i < 5; i++) {
        key16[i] = ints_to_int16(hex_to_int[j++],hex_to_int[j++],hex_to_int[j++]);
        cout << "0x" << hex << key16[i] << " ";
    }
    cout << endl;
}

输出

0xabcdef0123456789abcd

0xabcd 0xef01 0x2345 0x6789 0xabcd

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)