cancel
Showing results for 
Search instead for 
Did you mean: 

Bit alingment

Rundumeli
Associate II

Hi everyone

I have a problem with a data structure I really want to use, because I would heavenly benefit from the easy access, that it would provide.

 

/* * myTypes.h * * Created on: 02.05.2023 * Author: */ #ifndef INC_MYTYPES_H_ #define INC_MYTYPES_H_ #ifdef __cplusplus extern "C" { #endif #pragma pack(push, 1) typedef union { struct { bool b0 : 1; bool b1 : 1; bool b2 : 1; bool b3 : 1; bool b4 : 1; bool b5 : 1; bool b6 : 1; bool b7 : 1; bool b8 : 1; bool b9 : 1; bool b10 : 1; bool b11 : 1; bool b12 : 1; bool b13 : 1; bool b14 : 1; bool b15 : 1; bool b16 : 1; bool b17 : 1; bool b18 : 1; bool b19 : 1; bool b20 : 1; bool b21 : 1; bool b22 : 1; bool b23 : 1; bool b24 : 1; bool b25 : 1; bool b26 : 1; bool b27 : 1; bool b28 : 1; bool b29 : 1; bool b30 : 1; bool b31 : 1; }BIT; bool BOOL[32]; uint8_t INT8[4]; uint16_t INT16[2]; uint32_t INT32; } bitarray32; #pragma pack(pop) #ifdef __cplusplus } #endif #endif /* INC_MYTYPES_H_ */
View more

 

The access via INT32, INT16 , INT8 and BIT is working, however over the BOOL array not really.

I understand, that I could have memory alignment issues, especially because I'm using this in c++. But that's why I have defined this types in c.
I tried to enforce alignment with #pragma pack(push, 1), but I'm way out of my knowledge here.

Can someone guide me through this. Thanks in advance.

3 REPLIES 3

C does not have a bit array type.

Typically if you want mechanical indexing you'd use the uint32_t type, and shift a bit mask. For a larger array you'd decompose a row/column based on the size of the type you're holding it in.

https://www.sanfoundry.com/c-program-implement-bit-array/

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

Ohhh if it is only because I forgot to include stdbool.h, ... I would turn mad^^ Thanks for the reminder!

I know bit shifting, but as this example shows, indexing via the the bool/union/struct, the code gets much more readable. see:

//direct indexing via bool array ptr_sequencer->ref_outputMaster.currentOutput.BOOL[chanelIndex] = channel.pattern.BOOL[32- ptr_sequencer->ref_clkMaster.time]; //same result but with masks ptr_sequencer->ref_outputMaster.currentOutput.INT8 = (channel.pattern.INT32 >> (32-ptr_sequencer->ref_clkMaster.time) & 1) << chanelIndex;

 

Yeah no. that's not what caused the faulty behaviour....