Adding extra bits in c bitfield -


i have update following structure add street information in structure.

typedef struct address_tag {     union {         struct {             unsigned state   : 20;                  unsigned city    : 10;              unsigned unused :2;         };          uint32_t address;     };  } defect_address_t; 

i used unused bits , used 2 bits street:

typedef struct address_tag {     union {         struct {             unsigned state   : 20;                  unsigned city    : 10;              unsigned street :2;         };          uint32_t address;     };  }address_t; 

the problem have reserve 10 bits street instead of 2. there way can add it? have make sure address 32 bits.

the obvious solution take bits others, such state. if only, need no more 6 bits state. need bits state in city field, anyway.

however, if concern memory (occupying no more 32 bits), can add possibilities enum, , have functions extract state/city/street.

typedef enum state_city_street_t {     california,     california_sanfrancisco = california,     california_sanfrancisco_missionstreet = california_sanfrancisco,     california_sanfrancisco_howardstreet,     california_sanfrancisco_end,     california_mountainview = california_sanfrancisco_end,     california_mountainview_castrostreet = california_mountainview,     ...     california_end,     nevada = california_end,     nevada_lasvegas = nevada,     nevada_lasvegas_thestrip = nevada_lasvegas,     ... } state_city_street_t;  #define get_const(state, city, street) state##_##city##_##street #define is_state(value, state) ((value >= state) && (value < state##_end)) 

this guarantees best memory usage (no combination of bits wasted). main tradeoff being harder access of individual fields, both in terms of performance , code clarity. ideally, enum autogenerated.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -