5bit field

frijofrancis007 2,434 views 6 slides Jan 30, 2014
Slide 1
Slide 1 of 6
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6

About This Presentation

No description available for this slideshow.


Slide Content

Bit Field

Bit Field
•C allow integer members to be stored into
memory spaces smaller than the compiler
would ordinarily allow.
•These space-saving structure members are
called bit fields, and their width in bits can be
explicitly declared.
•A structure declaratorcan also be a specified
number of bits, called a "bit field."
•Its length is set off from the declaratorfor the
field name by a colon.
•A bitfield is interpreted as an positiveintegral
type.

Bit Field
•Example
•structmybitfields
•{
• unsigned short a : 4;
• unsigned short b : 5;
• unsigned short c : 7;
•} test;
•main( )
•{
• clrscr();
• test.a= 2;
• test.b= 31;
• test.c= 0;
• printf("%d %d %d",test.a,test.b,test.c);
• getch();
•}
•the bits would be arranged as follows:
•00000001 11110010
•Cccccccbbbbbaaaa

Bit Field
•structpacked_struct{
• unsigned intf1:1;
• unsigned intf2:1;
• unsigned intf3:1;
• unsigned intf4:1;
• unsigned inttype:4;
• unsigned intfunny_int:9;
•} pack;
•Here the packed_structcontains 6 members: Four 1 bit flags f1..f3, a 4
bit type and a 9 bit funny_int.
•C automatically packs the above bit fields as compactly as
possible, provided that the maximum length of the field is less than or
equal to the integer word length of the computer.
•If this is not the case then some compilers may allow memory overlap
for the fields whilst other would store the next field in the next word
(see comments on bit fielsportability below).

Bit Field
•Access members as usual via:
•pack.type= 7;
•NOTE:
•Only n lower bits will be assigned to an n bit
number. So type cannot take values larger than
15 (4 bits long).
•Bit fields are always converted to integer type
for computation.
•You are allowed to mix ``normal'' types with bit
fields.
•The unsigned definition is important -ensures
that no bits are used as a flag.

Bit Field
structDISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1;
unsigned disk_spinning:1;
unsigned write_protect:1;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};
Tags