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
  • You can try a "bit" array:

    
    #ifndef BIT_ARRAY_H
    #define BIT_ARRAY_H
    
    #include <limits.h>
    
    #define CHAR_BIT 8
    
    #define BITMASK(b)      (1 << ((b) % CHAR_BIT))
    #define BITSLOT(b)      ((b) / CHAR_BIT)
    #define BITSET(a, b)    ((a)[BITSLOT(b)] |= BITMASK(b))
    #define BITCLEAR(a, b)  ((a)[BITSLOT(b)] &= ~BITMASK(b))
    #define BITTEST(a, b)   ((a)[BITSLOT(b)] & BITMASK(b))
    #define BITNSLOTS(nb)   ((nb + CHAR_BIT - 1) / CHAR_BIT)
    
    #endif
    

    usage:

    
    BITSET(g_nand_flash_defective_physical_blocks, l_logical_block ) ;
    
    if (BITTEST(g_nand_flash_defective_physical_blocks, l_logical_block ) )
    {
    }
    

Reply
  • You can try a "bit" array:

    
    #ifndef BIT_ARRAY_H
    #define BIT_ARRAY_H
    
    #include <limits.h>
    
    #define CHAR_BIT 8
    
    #define BITMASK(b)      (1 << ((b) % CHAR_BIT))
    #define BITSLOT(b)      ((b) / CHAR_BIT)
    #define BITSET(a, b)    ((a)[BITSLOT(b)] |= BITMASK(b))
    #define BITCLEAR(a, b)  ((a)[BITSLOT(b)] &= ~BITMASK(b))
    #define BITTEST(a, b)   ((a)[BITSLOT(b)] & BITMASK(b))
    #define BITNSLOTS(nb)   ((nb + CHAR_BIT - 1) / CHAR_BIT)
    
    #endif
    

    usage:

    
    BITSET(g_nand_flash_defective_physical_blocks, l_logical_block ) ;
    
    if (BITTEST(g_nand_flash_defective_physical_blocks, l_logical_block ) )
    {
    }
    

Children