Y
Y
Yu Yu2016-03-01 17:34:40
C++ / C#
Yu Yu, 2016-03-01 17:34:40

How to correctly assemble a word from bits?

Like this

result = state[0]<<0|state[1]<<1|state[2]<<2|state[3]<<3|state[4]<<4|state[5]<<5|state[6]<<6|state[7]<<8|
state[8]<<8|state[9]<<9|state[10]<<10|state[11]<<11|state[12]<<12|state[13]<<13|state[14]<<14|state[15]<<15;

It works
like this
for (iterator = 0; iterator < 16; iterator++){
result |= state[iterator]<<iterator;

Does not work.
I checked it on a piece of paper, everything seems to be fine. But the computer, when setting the first or last bit, gives the result
32769
Where could I be mistaken?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Vorontsov, 2016-03-01
@VNSB18E1

  • Hopefully result is initialized to zero and has a capacity greater than 16 bits (or unsigned)?
  • In general, from memory, the shift operation only works with constants, i.e. you can't write << i. Can be changed like this:
    for (iterator = 0; iterator < 16; iterator++){
    result = result<<1;
    if(state[iterator] > 0) result++;

    well, or ++, replace it with "OR" with a unit. You can even do "or" directly with state[iterator]. Or replace the shift by multiplying the counter by 2 at each iteration (you need a separate variable) and plus it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question