-2

我编写了以下代码,将数据从一个字符串(字符数组)转换并存储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++;
}
4

1 回答 1

1

是的,这里有一些多余的变量。

您拥有两者counter,并且两者都i做完全相同的事情并始终保持相同的价值。你有indexWrite它总是正好是它们的一半(每个整数除法)。

您也移动得太远(16 位而不是 8 位)。

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

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

虽然我可能会这样做以避免N冗余|=操作:

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

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

std::copy如果您的字节序适合它,您可能还希望考虑对整个 dang 缓冲区进行简单处理。

于 2020-04-20T12:39:28.030 回答