Bit Manipulation Using Structure in C Programming Language
Bit Operations using Structure !!!
Suppose we want to store the gender of the person , then instead of wasting the complete byte we can manipulate single bit. We can consider Single bit as a flag. Gender of Person can be stored as [M/F] . By Setting the flag bit 1 we can set Gender as “Male” and “Female” by setting bit as 0
- To pack Several data objects in the single memory word , Bits are used.
- Flags can be used in order to store the Boolean values ( T / F ).
- A method to define a structure of packed information is known as bit fields.
Syntax : Bit Manipulation
struct databits { int b1 : 1; int b2 : 1; int b3 : 1; int b4 : 4; int b5 : 9; }data1;
Explanation :
- In the above example, we can say that we have allocated specific number of bits to each structure member.
- Integer can store 2 bytes (*) , so 2 bytes are manipulated in bits and 1 bit is reserved for b1. Similarly b2,b3 will get single bit.
- Similarly we can structure efficiently to store boolean values or smaller values that requires little membory.
How to access the Individual Bits ?
data1.b1 data1.b2 data1.b3 data1.b4 data1.b5
We can access the individual structure member by using dot operator. Each data member of structure can be accessed by using tag name followed by dot and structure member.
How to initialize Structure ?
struct databits { - - - - - - }data1 = { 1,1,0,10,234 };
Initialized Result -
data1.b1 = 1 data1.b2 = 1 data1.b3 = 0 data1.b4 = 10 data1.b5 = 234