【发布时间】: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