1

excuse me if this is a newbie question:

I have four uint8_t variables: first, second, third, fourth.

My objective is to put them in a uint32_t, such as that the uint32_t will be composed as:

fourth-third-second-first, but only putting the first 7 less significant bits of every uint8_t into the uint32_t, and so padding the 4 most significant bits of the uint32_t with zeros.

For example, let's say:

first = 10000000 -> I'm gonna put 0000000

second = 10011001 -> I'm gonna put 0011001

third = 10101010 -> I'm gonna put 0101010

fourth = 01111111 -> I'm gonna put 1111111

The uint32_t should end up being:

00001111 11101010 10001100 10000000

That is: 4zerosOfPadding-fourth-third-second-first

How can I do this using masking and shifting?

Edit: What I tried is:

    uint32_t target = 0;
    uint8_t first = 128, second = 153, third = 170, fourth = 127;

    //127 = 0111 1111
    target = (first & 127);
    target = (target >> 7) | (second & 127);
    target = (target >> 14) | (third & 127);
    target = (target >> 21) | (fourth & 127);

But what I get with this is that I just overwrite target everytime with the 7 less significant bits of the current uint8_t. I can't understand how to use shifting properly. Thanks everyone for the help.

  • 1
    What did you try, as it seems you know about the right tools (masking, shifting), how to do that? – πάντα ῥεῖ Feb 05 '22 at 10:59
  • 1
    So, you want to compress four 8bit values into a 32bit target by stripping the high bit of each 8bit value, forming the low 28bits of your 32bit result, and the high 4 bits to zero. Seems logical. Can you [edit your question](https://stackoverflow.com/posts/70997326/edit) to show what you tried and what the results were ? – WhozCraig Feb 05 '22 at 11:01
  • @WhozCraig I edited as you suggested, thanks for helping – sine nomine Feb 05 '22 at 12:47
  • @πάντα ῥεῖ I edited as you suggested, thanks for helping – sine nomine Feb 05 '22 at 12:47
  • 3
    Your shifts are the wrong direction. Every one of those `target >>` should be `target <<` . As you have it now, you are pushing the bits you just set in the low octet of `target` out immediately after you put them in – WhozCraig Feb 05 '22 at 12:58
  • 3
    As @WhozCraig commented, you should shift left not right. You should also shift 7 bits each time. The shifts are cumulative. So to get the result you want start with the fourth, and on to the first. Also it's better style to use 0x7F instead of 127. – YuvGM Feb 05 '22 at 13:16

0 Answers0