是什么在C数组,使位操作的最有效方法 [英] What's the most efficient way to make bitwise operations in a C array

查看:116
本文介绍了是什么在C数组,使位操作的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C数组,如:

 字符BYTE_ARRAY [10];

和另一个充当面膜:

 字符BYTE_MASK [10];

我想办得到另一个数组,它是从第一加使用按位操作的第二个的结果,在每个字节

什么是做到这一点的最有效方法是什么?

谢谢您的回答。


解决方案

 为(I = 10;我 - 大于0;)
    result_array [I] = BYTE_ARRAY [1] - 放大器; BYTE_MASK [I]


  • 倒退pre-负载处理器高速缓存行。

  • 包括比较可以节省一些说明。
  • 减量

这将为所有阵列和处理器的工作。但是,如果你知道你的数组是字对齐的,更快的方法是将转换为更大的类型,做同样的计算。

例如,假设 N = 16 而不是 N = 10 。那么这将是更快:

  uint32_t的* input32 =(uint32_t的*)BYTE_ARRAY;
uint32_t的* mask32 =(uint32_t的*)BYTE_MASK;
uint32_t的* result32 =(uint32_t的*)result_array;
为(ⅰ= 4;我 - 大于0)
    result32 [I] = input32 [1] - 放大器; mask32 [I];

(当然你需要为 uint32_t的合适的类型,如果 N 不是2的幂你需要清理的开始和/或结束,以使32位的东西是对齐的。)

变化:问题明确要求,结果被放置在一个单独的数组,但它几乎肯定会更快修改就地输入数组

I have a C array like:

char byte_array[10];

And another one that acts as a mask:

char byte_mask[10];

I would like to do get another array that is the result from the first one plus the second one using a bitwise operation, on each byte.

What's the most efficient way to do this?

thanks for your answers.

解决方案

for ( i = 10 ; i-- > 0 ; )
    result_array[i] = byte_array[i] & byte_mask[i];

  • Going backwards pre-loads processor cache-lines.
  • Including the decrement in the compare can save some instructions.

This will work for all arrays and processors. However, if you know your arrays are word-aligned, a faster method is to cast to a larger type and do the same calculation.

For example, let's say n=16 instead of n=10. Then this would be much faster:

uint32_t* input32 = (uint32_t*)byte_array;
uint32_t* mask32 = (uint32_t*)byte_mask;
uint32_t* result32 = (uint32_t*)result_array;
for ( i = 4 ; i-- > 0 ; )
    result32[i] = input32[i] & mask32[i];

(Of course you need a proper type for uint32_t, and if n is not a power of 2 you need to clean up the beginning and/or ending so that the 32-bit stuff is aligned.)

Variation: The question specifically calls for the results to be placed in a separate array, however it would almost certainly be faster to modify the input array in-place.

这篇关于是什么在C数组,使位操作的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆