This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Construct a byte from bits

Hello everybody,

I am very new to C language. In my project I get data serially from a port pin. I want to save the first 8 bits to one variable, another to second & so on. In all I want to save 32 bits in 4 bytes. Can you suggest C code.

I know it in assembly by using RRC or RLC, but how to achieve it in C?

Thanks

Parents
  • Consider unsigned long prefixes:

    b3 = (data_received & 0xFF000000ul) >> 24;
    


    Some compilers will complain about constants out of range if you don't tell they are long.
    Some compilers will complain about mixing of signed and unsigned if you don't tell that your constant is unsigned.

    Some compilers will like shift befure and, just so they can pick up a byte directly instead of having an 8-bit processor doing a 32-bit and operation. Not sure if Keil C51 will detect and optimize. Or even go one step further and skip the shift too - just pick up the relevant byte directly from memory.

Reply
  • Consider unsigned long prefixes:

    b3 = (data_received & 0xFF000000ul) >> 24;
    


    Some compilers will complain about constants out of range if you don't tell they are long.
    Some compilers will complain about mixing of signed and unsigned if you don't tell that your constant is unsigned.

    Some compilers will like shift befure and, just so they can pick up a byte directly instead of having an 8-bit processor doing a 32-bit and operation. Not sure if Keil C51 will detect and optimize. Or even go one step further and skip the shift too - just pick up the relevant byte directly from memory.

Children