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
  • Do not mix rotate and shift. Two completely different things that can be done at the bit level.

    Note that if efficiency isn't important, you can defined an unsigned 32-bit integer and shift in bits one-by-one:

    #include <stdiint.h>
    
    uint32_t n = 0;
    
    ...
    
    n <= 1;
    if (bit) n |= 1;
    

    Or potentially (if you want reversed order of the bits):

    n >>= 1;
    if (bit) n |= 0x80000000ul;
    

Reply
  • Do not mix rotate and shift. Two completely different things that can be done at the bit level.

    Note that if efficiency isn't important, you can defined an unsigned 32-bit integer and shift in bits one-by-one:

    #include <stdiint.h>
    
    uint32_t n = 0;
    
    ...
    
    n <= 1;
    if (bit) n |= 1;
    

    Or potentially (if you want reversed order of the bits):

    n >>= 1;
    if (bit) n |= 0x80000000ul;
    

Children
No data