我有一个长整数(即10001000110 ...)和一个带双值的数组(即{.5,.76,.34,...}),我想遍历整数的二进制表示并乘以每个数字及其在我的数组中的对应位置,并将它们加在一起(矩阵乘法):
就像:1 * .5 + 0 * .76 + 0 * .34 .....
用C做这件事的最佳方法是什么?
谢谢
像这样吗
int n = n_doubles;
double result = 0.0;
while (n--) {
if ((long_integer>>n)%2)
result += doubles[n_doubles - n];
}
编辑:问题尚不清楚,但是从作者的最新评论看来,这似乎是关于获取整数的位表示形式。
首先,您必须使用位掩码来获取整数的按位表示:
uint32_t theLongInt = <?>;
uint32_t mask = 0x00000001;
// bitwise representation of the integer theLongInt
uint8_t bits[30];
for(int i = 0; i < 30; i++) {
if ( (theLongInt & mask) == 1)
bits[i] = 1;
else
bits[i] = 0;
mask = mask << 1;
}
比您可以循环执行相加和相乘。
为了提高效率,请不要存储整数的按位表示,而是在单个for循环内进行操作。
与buddhabrot的答案类似,这更公然地将位和数组元素对齐,但将LSB与index[0]
对齐:
double result = 0.0;
for(int x=0; x<n_doubles; x++){
if(long_integer & (1<<x))
result += doubles[x];
}