代码之家  ›  专栏  ›  技术社区  ›  Engineer999

将字符数组转换为uCu160t数组C/C++

  •  -2
  • Engineer999  · 技术社区  · 6 年前

    我已经编写了下面的代码来转换和存储来自字符串(字符数组)的数据 str 在一个16位整数数组中调用 arr16bit

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

    我不想用索引 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++;
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Asteroids With Wings    6 年前

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

    你两个都有 counter i 它们做着完全相同的事情并且总是持有相同的价值。你已经 indexWrite 它总是正好是它们的一半(每整数除法)。

    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] <<= 16;
        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] << 16);
        arr16bit[(i/2)+1] |= str[i+1];
    }
    

    你也可以考虑一个简单的 std::copy 整个该死的缓冲区,如果你的端部适合的话。