给定一个十六进制字符的字符串, 我想从中创建一个字节数组。例如,给定字符串"1A2B3C",我希望我的数组包含0x1A,0x2B,0x3C。
我已经使用下面的代码使其工作,但是希望看到更有效率的做法。
(此时已经完成了字符串长度等的检查)。
// Go through the string
int k = 0;
stringstream s;
for (int i = 0; i < STRING_SIZE; i++)
{
// Get 2 digits at a time and store in a temp variable
s.str("");
s << key[k++];
s << key[k++];
char temp[2];
memcpy(temp, s.str().c_str(), 2);
// Get the hex value and store in final array
actualArray[i] = (unsigned char)strtol(temp, 0, 16);
}
stringstream
和memcpy
这些复杂而低效的操作,你可以直接使用const char temp[3] = {key[i], key[i+1]};
(并将i++
替换为i += 2
)。这里的3
是为了使字符串以零结尾。如果没有这个,调用strtol
就会产生未定义行为。 - Cheers and hth. - Alf