如何解决将 80 位十六进制数从 char 数组复制到 uint16_t 向量或数组
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 举报,一经查实,本站将立刻删除。