0

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.

I have an array of int values: int bitVal[8]

In my program, each of these values is 1 bit, within a byte. I need to create a loop which goes through each value, and bit shift the value into the int variable.

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; the result will be 0000 0100. Is there a way to set it so the shifted bit is a 1 instead of a 0?

1
  • Since t is 0 shifting it remains 0. The question is not very clear. int bitVal[8] is not in the code snippet, and the loop constraint is the curious i < 3;. Commented Feb 6, 2018 at 21:34

2 Answers 2

2

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:

result = 0;
for (i=0; i<8; i++)
{
    result = (result<<1) | bitVal[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. You're right, I was completely overthinking it T_T
1

Is there a way to set it so the shifted bit is a 1 instead of a 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 = (x << 1) | y;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.