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 Reply Children
  • Thanks. What I understand from these replies is:

    The routine suggested by christian crosa is to define a structure for storing 32 bits data, so that individual bits can be accessed. I got it, this will be very useful to me in future.

    The routine suggested by Tamir Michael is to manipulate bits (what I think). This code is not too much clear to me.

    My exact problem is that, the micro-controller is receiving 32 bits of data serially by two pins CLOCK & DATA. INT0 is connected to CLOCK whereas P3.3 is for DATA input. Now in the interrupt routine I want to shift the input data bits into an 8bit variable. Then next 8 bits in another variable & so on.

    So I need a way to rotate the variable bits left or right through DATA bit. I know there are operators such as << & >> to rotate bits, but they does rotate through carry or another bit.

  • This code is not too much clear to me.

    LOL. Well put. Comments are probably a foreign concept to him.

    Look at something like:

      Bit = CpuDataPin;
      ByteAccumulator = (ByteAccumulator<<1) | Bit;
    

  • 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;