Question:
what are bit fields?
kiran
2008-02-14 02:29:50 UTC
what are bit fields and what is the use of bit fields in a structure declaration?
Three answers:
rwid
2008-02-14 11:49:55 UTC
In C or C++, bit fields provide individual boolean flags to manipulate. There are numerous uses within a structure declaration. They can be used with file formats or even graphic images. Similar affects can be achieved with shifting and masking but bit fields allow direct labeled access to anticipated bit patterns.



A bit field is a commonly-used data structure used to compactly hold a set of Boolean flags. Instead of using Boolean variables for each flag, the flags are stored in a fixed-size data structure like an integer, whose size in bits is known. The Boolean flags are then stored in each bit of the data structure, minimizing memory usage.
angels
2008-02-14 11:04:57 UTC
"bits" as it sounds single smallest memory unit (location) provided on the disk when u write anything on the disk



structure declaration



it includes different datatypes all together .

i.e. float data type , integers ,characters etc all can be handelled together which is generally not possible in other types of "c - programming"

here the total bits (addition of all bits)alloted to the all the datatype is the size of the structure



structure basically means the database tables which we create in v. foxpro is declared as a structure in "c"
The Tadpole
2008-02-15 05:20:44 UTC
A bit field is the smallest represention of data in the computer. It will be either 0 or one.



A character (type char) is actually a byte which consists of 8 bits. In C language it is possible to go upto bit level programming. As an illustration I have created the following example. It reads a character and prints the bit representation of it. You can try the example (compiled and tested in with in VC++ env.) and work with some exercises similar to the one.



I hope you are familiar with what a union is, as I have included a union declaration as well. If any questions please get back.



#include

main()

{

struct bitflds

{

int egth:1;

int svth:1;

int sxth:1;

int ffth:1;

int frth:1;

int thrd:1;

int scnd:1;

int frst:1;

};



union unchar

{

struct bitflds uch;

char ch;

} scch;



/*

you can try running the executable with input values like

2, 4, 8, 16 etc., to see 10,100, 1000 etc in bit notation

*/

scanf("%d", &scch.ch);



/*

In order to get the value 1 when the bit is set I have 'AND'ed each of the bit-fields with 0x1. Otherwise the printed value of each of the bits with 1 will show as 37777...

*/

printf("bits of the character %d are: %o %o %o %o %o %o %o %o\n",scch.ch, scch.uch.frst&0x1, scch.uch.scnd&0x1, scch.uch.thrd&0x1, scch.uch.frth&0x1, scch.uch.ffth&0x1, scch.uch.sxth&0x1, scch.uch.svth&0x1, scch.uch.egth&0x1);

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...