我编写了以下代码,将数据从一个字符串(字符数组)转换并存储str
到一个 16 位整数数组中,称为arr16bit
该代码有效。但是,我想说有一种更好或更简洁的方法来实现这个逻辑,使用更少的变量等。
我不想使用 indexi
来获取模数 % 2,因为如果使用 little endian,我有相同的算法,但从i
字符串的最后一个索引开始并倒计时而不是向上倒计时。任何建议表示赞赏。
// assuming str had already been initialised before this ..
int strLength = CalculateStringLength(str); // function implementation now shown
uint16_t* arr16bit = new uint16_t[ (strLength /2) + 1]; // The only C++ feature used here , so I didn't want to tag it
int indexWrite = 0;
int counter = 0;
for(int i = 0; i < strLength; ++i)
{
arr16bit[indexWrite] <<= 8;
arr16bit[indexWrite] |= str[i];
if ( (counter % 2) != 0)
{
indexWrite++;
}
counter++;
}