【问题标题】:Converting char array to uint16_t array C/C++将 char 数组转换为 uint16_t 数组 C/C++
【发布时间】:2020-04-20 12:26:42
【问题描述】:

我编写了以下代码,将数据从名为str的字符串(字符数组)转换并存储到名为arr16bit的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++;
}

【问题讨论】:

  • new uint16_t( (strlen /2) + 1)一个 uint16_t 值分配内存,并将该单个值初始化为 (strlen /2) + 1
  • 您没有具体问题,但希望获得有关如何改进代码的建议。所以问题更适合Code Review SE。此外,这是 C++ 代码,而不是 C 代码。
  • 问题是什么?
  • @Someprogrammerdude 是的,你是对的。我更正了它[]
  • "如果使用 little endian,我有相同的算法,但我从字符串的最后一个索引开始倒计时而不是倒计时。" 不,它没有;仅交换每对中的字节

标签: c++ arrays string bit-shift byte-shifting


【解决方案1】:

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

您同时拥有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

【讨论】:

  • 感谢您的回复。我意识到我犯了一个错误,在我的问题中意味着
  • @Engineer999 这不是通常理解的字节顺序。
猜你喜欢
  • 2021-11-16
  • 1970-01-01
  • 2016-04-07
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2012-04-29
  • 1970-01-01
相关资源
最近更新 更多