-
Notifications
You must be signed in to change notification settings - Fork 160
/
bitfield.c
50 lines (35 loc) · 878 Bytes
/
bitfield.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
# bitfield
Gives support for fields which contain a single bit in the language.
*/
#include "common.h"
int main(void) {
struct S {
unsigned b1 : 1;
unsigned b2 : 2;
unsigned b3 : 3;
/* padding untill next int is added automatically because */
/* next data is not a bitfield and accesses is faster if it is aligned */
int i;
unsigned b4 : 1;
/* manually adds padding untill next field */
/* even if it is a bitfield */
unsigned : 0;
unsigned b5 : 1;
} s ;
assert(sizeof(struct S) == 16);
s.b1 = 1;
assert(s.b1 == 1);
/* WARN */
/* overflow */
/* truncate */
/*s.b1 = 2;*/
int i = 2;
s.b1 = i;
assert(s.b1 == 0);
/* Only takes lsb. */
i = 3;
s.b1 = i;
assert(s.b1 == 1);
return EXIT_SUCCESS;
}