0

我正在执行以下代码以从数组中读取 6 字节的特定值。对我来说,以下内容看起来很丑。我在 Little Endian 处理器上运行此代码。有什么方法可以让它更优雅。

temp_ts = (ptr[ts_offset]);
new_ts = temp_ts << 40;

temp_ts = (ptr[ts_offset + 1]);
new_ts |= temp_ts << 32;

temp_ts = (ptr[ts_offset + 2]);
new_ts |= temp_ts << 24;

temp_ts = (ptr[ts_offset + 3]);
new_ts |= temp_ts << 16;

temp_ts = (ptr[ts_offset + 4]);
new_ts |= temp_ts << 8;

temp_ts = (ptr[ts_offset + 5]);
new_ts |= temp_ts << 0;

注意:代码运行良好。这只是样式问题。

4

3 回答 3

3

您可以将其编码为循环并让编译器进行展开:

for (new_ts = i = 0; i < 6; i++) 
  new_ts = (new_ts << 8) | ptr[ts_offset + i];

为了它的价值,我用gcc 4.3.6and编译了这个-O4。它确实很好地展开。

于 2013-08-30T04:35:14.167 回答
1

尝试以下

int offset = 0;
int shift = 40;
while (offset <= 5) { 
  temp_ts = ptr[ts_offset + offset];
  new_ts |= temp_ts << shift;
  offset++;
  shift -= 8;
}
于 2013-08-30T04:31:47.160 回答
1

我喜欢你的多余<< 0;再次为了对称,我还添加了+ 0

p = ptr;
o = ts_offset;
new_ts = (p[o + 0] << 40) | (p[o + 1] << 32) | (p[o + 2] << 24) |
         (p[o + 3] << 16) | (p[o + 4] <<  8) | (p[o + 5] <<  0);

或者添加一个简化(其他人没有看到):

unsigned char* p = ptr + ts_offset;
new_ts = (p[0] << 40) | (p[1] << 32) | (p[2] << 24) |
         (p[3] << 16) | (p[4] <<  8) | (p[5] <<  0);
于 2013-08-30T04:53:53.727 回答