很简短,我在理解此代码的工作方式时遇到了问题,它比20条左右的代码要获得相同的结果要有效得多。我了解左移应该如何工作,以及按位运算还是可以的,但是我希望能获得一点指导,以了解两者如何组合在一起以使for循环中的行起作用。 代码旨在获取给定大小(计数)的位数组,并返回这些位的整数值。
unsigned binary_array_to_numbers(const unsigned *bits, size_t count) {
unsigned res = 0;
for (size_t i = 0; i < count; i++)
res = res << 1 | bits[i];
return res;
}
编辑:根据要求,我的新手解决方案仍然通过了所有测试:添加的是可能分配给位的示例[]
unsigned binary_array_to_numbers(const unsigned *bits, size_t count)
{
int i, j = 0;
unsigned add = 0;
for (i = count - 1; i >= 0; i--){
if(bits[i] == 1){
if(j >= 1){
j = j * 2;
add = add + j;
}
else{
j++;
add = add + j;
}
}
else {
if( j>= 1){
j = j * 2;
}
else{
j++;
}
}
}
return add;
}
void main(){
const unsigned bits[] = {0,1,1,0};
size_t count = sizeof(bits)/sizeof(bits[0]);
binary_array_to_numbers(bits, count);
}
答案 0 :(得分:1)
明细:
0111(7) << 1 = 1110(14)
让我们尝试检查您输入的案例:
bits = {0, 1, 0, 1};
count = 4;
unsigned binary_array_to_numbers(const unsigned *bits, size_t count) {
unsigned res = 0;
for (size_t i = 0; i < count; i++)
res = res << 1 // (a)
res = res | bits[i]; /* (b) according to rhubarbdog answer */
return res;
}
迭代0:
-位[i] = 0;
-(a)res = b0; (左移0)
-(b)res = b0; (按位或为0)
迭代1:
-位[i] = 1;
-(a)res = b0; (左移0)
-(b)res = b1; (按位或为1)
迭代2:
-位[i] = 0;
-(a)res = b10; (左移1-十进制值为2)
-(b)res = b10; (按位或为0)
迭代3:
-位[i] = 1;
-(a)res = b100; (左移1-十进制值为4)
-(b)res = b101; (按位或为1)
res
的最终结果是二进制的(101)和十进制的(5)
注意:必须使用unsigned
,因为如果MSB为1
希望有帮助...
答案 1 :(得分:0)
将其视为2个操作,我将res= ...
重写为2行
res = res << 1
res = res | 1
首次通过res
设置为1,下一次将其移至*2
时是因为现在甚至是+1