将 char 数组转换为 uint16_t 数组 C/C++

Converting char array to uint16_t array C/C++

我编写了以下代码,将名为 str 的字符串(字符数组)中的数据转换并存储到名为 arr16bit[=17= 的 16 位整数数组中]

代码有效。但是,我想说有更好或更简洁的方法来实现此逻辑,使用更少的变量等。

我不想使用索引 i 来获取模数 % 2,因为如果使用小端,我有相同的算法但是 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++;
}

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

您有 counteri,它们做完全相同的事情并且始终保持相同的值。你有 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];
}

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