简体   繁体   English

位的位移位数组为Int变量

[英]Bit-Shift array of Bits into Int Variable

So I'm not sure if this is the easiest way to accomplish what my end goal is, so if anyone has a better suggestion, feel free to throw it at me. 因此,我不确定这是否是实现最终目标的最简单方法,因此,如果有人有更好的建议,请随时向我提出。 I've tried searching both on here, and with Google, but I can't seem to figure out how to do this. 我已经尝试过在这里和Google上进行搜索,但是似乎无法弄清楚该怎么做。

I have an array of int values: int bitVal[8] 我有一个int bitVal[8]数值数组: int bitVal[8]

In my program, each of these values is 1 bit, within a byte. 在我的程序中,每个值都是一个字节内的1位。 I need to create a loop which goes through each value, and bit shift the value into the int variable. 我需要创建一个遍历每个值的循环,然后将值移入int变量。

I tried this as a simple test: 我尝试将其作为一个简单的测试:

int t = 0;
int e = 1;
for(int i = 0; i < 3; i++) {
    t <<= e;
    printf("%d\n", t);
}

Now I know that if I had a variable that had a byte value of 0000 0010 and I do var <<= 1; 现在我知道,如果我有一个字节值为0000 0010的变量,并且执行了var <<= 1; the result will be 0000 0100 . 结果将是0000 0100 Is there a way to set it so the shifted bit is a 1 instead of a 0? 有没有办法设置它,使移位后的位是1而不是0?

You're probably overthinking it. 您可能想得太多。 You can shift in one bit at a time, regardless whether it is a 0 or 1. All it needs is a loop such as this: 不管它是0还是1,您都可以一次移入一位。它只需要一个这样的循环:

result = 0;
for (i=0; i<8; i++)
{
    result = (result<<1) | bitVal[i];
}

Is there a way to set it so the shifted bit is a 1 instead of a 0? 有没有办法设置它,使移位后的位是1而不是0?

No, not as such. 不,不是这样。 Instead, what you do is shift the target value to make room, and then combine with the value you want to add. 相反,您要做的是移动目标值以腾出空间,然后将其与要添加的值合并。 For example, if x is your accumulation variable and y contains a value that you are certain is either 0 or 1, then you might do this: 例如,如果x是您的累加变量,并且y包含一个确定为0或1的值,则可以这样做:

x = (x << 1) | y;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM