C51: Order of Bitfields
Information in this article applies to:
QUESTION
What direction does the compiler define bitfields? Is it LSB to
MSB or the reverse.
ANSWER
The compiler defines bitfields from the least significant bit
(LSB) to the most significant bit (MSB).
In the following example listing, you can see that the bits are
arranged from the highest order byte to the lowest order byte and
within each byte, from the LSB to the MSB.
The Module Information shows that the data size is 2 bytes (16
bits). This is because the structure was declared with int (or
unsigned int). This causes 1-byte to be wasted if you use 8 bits or
less. Declaring the structure with "unsigned char" will result in a
data size of 1 byte (8 bits).
stmt level source
1 typedef struct
2 {
3 unsigned int bit_0 : 1; // Byte 1, Bit 0
4 unsigned int bit_1 : 1; // Byte 1, Bit 1
5 unsigned int bit_2 : 1; // Byte 1, Bit 2
6 unsigned int bit_3 : 1; // Byte 1, Bit 3
7 unsigned int bit_4 : 1; // Byte 1, Bit 4
8 unsigned int bit_5 : 1; // Byte 1, Bit 5
9 unsigned int bit_6 : 1; // Byte 1, Bit 6
10 unsigned int bit_7 : 1; // Byte 1, Bit 7
11 unsigned int bit_8 : 1; // Byte 0, Bit 0
12 unsigned int bit_9 : 1; // Byte 0, Bit 1
13 unsigned int bit_10: 1; // Byte 0, Bit 2
14 unsigned int bit_11: 1; // Byte 0, Bit 3
15 unsigned int bit_12: 1; // Byte 0, Bit 4
16 unsigned int bit_13: 1; // Byte 0, Bit 5
17 unsigned int bit_14: 1; // Byte 0, Bit 6
18 unsigned int bit_15: 1; // Byte 0, Bit 7
19 }bit_st;
20
21 bit_st x;
22
23
24 void main(void)
25 {
26 1 x.bit_0 = 1;
27 1 x.bit_1 = 1;
28 1 x.bit_8 = 1;
29 1 x.bit_15 = 1;
30 1
31 1 while(1);
32 1 }
; FUNCTION main (BEGIN)
; SOURCE LINE # 24
; SOURCE LINE # 25
; SOURCE LINE # 26
0000 850000 R MOV x,x
0003 E500 R MOV A,x+01H
0005 4401 ORL A,#01H
0007 F500 R MOV x+01H,A
; SOURCE LINE # 27
0009 850000 R MOV x,x
000C 4402 ORL A,#02H
000E F500 R MOV x+01H,A
; SOURCE LINE # 28
0010 FF MOV R7,A
0011 E500 R MOV A,x
0013 4401 ORL A,#01H
0015 F500 R MOV x,A
0017 8F00 R MOV x+01H,R7
; SOURCE LINE # 29
0019 4480 ORL A,#080H
001B F500 R MOV x,A
001D 8F00 R MOV x+01H,R7
001F ?C0001:
; SOURCE LINE # 31
001F 80FE SJMP ?C0001
; FUNCTION main (END)
SEE ALSO
Last Reviewed: Thursday, February 25, 2021