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
  • I don't use C51 but this might help. Bit fields usually are assigned as an int which would give you the first 4 members in one int, the 5th member in the 2nd int and the last in it's own byte (2 + 2 + 1 = 5). If padding is added it could become 6 bytes.

    typedef struct t_channel_info {
    	int target_temp:9;               // byte 1&2
    	unsigned char control_mode:2;    // byte 2
    	unsigned char status:2;          // byte 2
    	unsigned char warming:1;         // byte 2
    	int current_temp:9;              // byte 3&4
    	unsigned char warm_proportion;   // byte 5
    } t_channel_info;

    It is possible C51 can put bit fields in bytes which might give you;
    typedef struct t_channel_info {
    	int target_temp:9;               // byte 1&2
    	unsigned char control_mode:2;    // byte 3
    	unsigned char status:2;          // byte 3
    	unsigned char warming:1;         // byte 3
    	int current_temp:9;              // byte 4&5
    	unsigned char warm_proportion;   // byte 6
    } t_channel_info;
    Access each of the members in some test code and look at the assembly language to figure what is happening.
    Best luck
    Scott




Reply
  • I don't use C51 but this might help. Bit fields usually are assigned as an int which would give you the first 4 members in one int, the 5th member in the 2nd int and the last in it's own byte (2 + 2 + 1 = 5). If padding is added it could become 6 bytes.

    typedef struct t_channel_info {
    	int target_temp:9;               // byte 1&2
    	unsigned char control_mode:2;    // byte 2
    	unsigned char status:2;          // byte 2
    	unsigned char warming:1;         // byte 2
    	int current_temp:9;              // byte 3&4
    	unsigned char warm_proportion;   // byte 5
    } t_channel_info;

    It is possible C51 can put bit fields in bytes which might give you;
    typedef struct t_channel_info {
    	int target_temp:9;               // byte 1&2
    	unsigned char control_mode:2;    // byte 3
    	unsigned char status:2;          // byte 3
    	unsigned char warming:1;         // byte 3
    	int current_temp:9;              // byte 4&5
    	unsigned char warm_proportion;   // byte 6
    } t_channel_info;
    Access each of the members in some test code and look at the assembly language to figure what is happening.
    Best luck
    Scott




Children
No data
More questions in this forum