|  |  | | This article uses a union and two bitfields as flags.
The example program asks you if you are a boy or girl, also asks your name and your age.
Your name is saved in a union, your age in a structure and your gender in a structure that includes two bitfields , int boy:1 and int girl:1 .The possible combinations are :
int boy:1=1 and int girl:1=0 , int boy:1=0 and int girl:1=1 .
The program receives your age using scanf() function . scanf() terminates when an unrecognized character is received to the buffer of the i/o stream. For example, hiting at hyperterminal your age 22 and after it you hit a or 'ENTER' scanf() terminates. But the unrecognized character remains in the i/o stream buffer!
See Keil scanf() termination
The remaining character in the i/o buffer generates a problem if the next, after scanf() is a gets(). gets() receives the remaining character and terminates!
A simple solution is to use another gets() before gets() , sending the remaining character to the rubbish!
The C code The result
Exercise. A important feature of the C language is the ability to cast an address to point to an appropriate type (to a character or to an integer etc.). Using this feature we can give names to the bits of an integer or of a register for example .
Say that we have a structure like
struct g {
int gen;
} gender;
We can give a name to each one of the 16 bits of the integer gen following the steps:
Step 1
We difine a new type as:
typedef struct
{
unsigned int bit0 : 1;
unsigned int bit1 : 1;
unsigned int bit2 : 1;
unsigned int bit3 : 1;
unsigned int bit4 : 1;
unsigned int bit5 : 1;
unsigned int bit6 : 1;
unsigned int bit7 : 1;
unsigned int bit8 : 1;
unsigned int bit9 : 1;
unsigned int bit10 : 1;
unsigned int bit11 : 1;
unsigned int bit12 : 1;
unsigned int bit13 : 1;
unsigned int bit14 : 1;
unsigned int bit15 : 1;
} T;
As you see it is a structure that includes 16 bitfiels ,1 bit long each, of 16 integers named bito...bit15.
Step 2 We cast the poiner &(gender.gen) to a pointer of T type and selecting for example bit1.
Now we are ready to give a name using #define like:
#define BOY ((T*)(&(gender.gen))->bito
#define GIRL ((T*)(&(gender.gen))->bit1
See also pages 85,86 and 87 of Ted Van Sickle's book.
So, rewrite the above program of this article giving bitfield names to the bits of an integer included to a structure named gender.
The c code The result
Previous code lines are included as comments for comparison.
|
|
|