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

struct with members' sizes

I'm using C51 v3.20, and when I compiled the following structure, the compiler allocates 6 bytes for it.

typedef struct t_channel_info {
	int target_temp:9;
	unsigned char control_mode:2;
	unsigned char status:2;
	unsigned char warming:1;
	int current_temp:9;
	unsigned char warm_proportion;
} t_channel_info;

Should not it allocate only (9+2+2+1+9+8)/8=4 bytes?

But, when I partition a 9-bit integer to 8 and 1 bits chars, the size reduces to 5 bytes.

Is there an explanation?

Parents
  • Since you have control over the layout, I suggest the following modification to reduce code size and increase speed.

    typedef struct tt_channel_info {
    	int target_temp:9;  //keep the fields > 8 bits at int offset 0
    	unsigned int warm_proportion:7;
    
    	int current_temp:9; //keep the fields > 8 bits at int offset 0
    	unsigned int control_mode:2;
    	unsigned int status:2;
    	unsigned int warming:1;
    } tt_channel_info;
    
    
    
    

Reply
  • Since you have control over the layout, I suggest the following modification to reduce code size and increase speed.

    typedef struct tt_channel_info {
    	int target_temp:9;  //keep the fields > 8 bits at int offset 0
    	unsigned int warm_proportion:7;
    
    	int current_temp:9; //keep the fields > 8 bits at int offset 0
    	unsigned int control_mode:2;
    	unsigned int status:2;
    	unsigned int warming:1;
    } tt_channel_info;
    
    
    
    

Children