How do I represent bit information in C?

I need to store a value from 0 to 15 in C, 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a limitation here

+5
source share
6 answers

Consider use char. Yes, it is 8 bits, but you can use bit shift operators ( <<and >>) to store values ​​in the remaining 4 bits.

Edit: The comments below are unsigned charpreferable charto avoiding sign bit problems.

+7
source

bitfield 4 , , , - .

+4

4- , 8- , 4- , temp, , - , :

uint8_t var_both;
uint8_t temp = (var_both >> 4) & 0x0F; // For first value
temp = var_both & 0x0F; // For second value
+3

Chris Lutz, , , : unsigned char myOneBitVariable:1; "unsigned char MyFourBitVariable: 4". , , , ..

. - 4 8 , . . GCC __attribute__((aligned(x))), MSVC - __declspec(align(x)). , . MSVC #pragma pack(x): http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx. MSVC : http://msdn.microsoft.com/en-us/library/83ythb65(VS.80).aspx. GCC __attribute__ ((__packed__), , , . , , , Microsoft:


#ifndef _MSC_VER
#error This alignment solution / packing solution is only valid on MSC
#endif /* ifndef _MSC_VER */

#define M_ALIGN(x)    __declspec(align(x))

struct S64Bits
{
    unsigned char MyOneBitVariable:1;
    int My32BitInt;
};

// MSVC specific implementation of data-packing in a type.
#pragma pack(1)
struct S32Bits
{
    D_ALIGN(1) int My16BitVariable:16;
    D_ALIGN(1) unsigned char Padding8Bits;
    D_ALIGN(1) unsigned char MyOneBitVariable1:1;
    D_ALIGN(1) unsigned char MyOneBitVariable2:1;
    D_ALIGN(1) unsigned char MyOneBitVariable3:1;
    D_ALIGN(1) unsigned char MyOneBitVariable4:1;
    D_ALIGN(1) unsigned char MyFourBitVariable:4;
};
#pragma pack(pop)

'sizeof (S64Bits)' 8, . 'sizeof (S32Bits)' 4, . msvc 6 . . , . , , , , :


#define TEST_TYPE_SIZE(Type, Size) assert(sizeof(Type) == Size);

, . , , sizeof (mystructure), , , , . - - .

Karl Bielefeldt 4- uint8 , .

+2

. , :

struct two_nibbles {
  unsigned a :4;
  unsigned b :4;
}

You should name two variables x.aand x.b(but change xto anything), but you save a little space. You might want to check, I think the compiler made sure that sizeof(struct two_nibbles) == sizeof(char), but that may not be the case, so you might have to add more nibbles to make it worthwhile.

0
source

Do you ever want to accept the address of 4-bit values? If so, you need to store them in the "correct" data type, for example, char.

0
source

All Articles