When we declare the members in a struct and classes, a pre-determined size is allocated for the member variables. In C++, we can compress that allocated size using bit fields.
Bit Field is a feature in C++ for specifying the size of struct and class members so that they occupy a specific number of bits, not the default memory size.
For example, an integer takes 4 bytes of size but this size is large according to our requirements so we can change it to 2 bytes using bit fields.
Syntax of Bit Field in C++
In C++, we can define a bit field by specifying the data type and then the field name with the desired width in bits.
Bit-Field Syntax in Struct
struct StructName {
dataType fieldName : width;
// more bit-field members...
};
Bit-Field Syntax in Classes
class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
where width is the number of bits.
Note: It is to be noted that bit fields are only acceptable for integral data types.
Example of C++ Bit Fields
The following examples demonstrate the use of bit fields in both structures and classes.
Example 1: Bit Fields in Structures
In the below example, we will compare the size difference between the structure that does not specify bit fields and the structure that has specified bit fields.
C++
// C++ program to demonstrate the size occupied by a struct
// with and without bitfields
#include <iostream>
using namespace std;
// Define a struct without bit fields
struct Loan1 {
unsigned int principal;
unsigned int interestRate;
unsigned int period;
};
// Define a struct with bit-fields
struct Loan2 {
// principal variable can store maximum value of
// 1,048,575
unsigned int principal : 20;
// Maximum interest rate of 63
unsigned int interestRate : 6;
// Maximum period of 63 months
unsigned int period : 6;
};
int main()
{
// printing the size of both structures
cout << "Size of Structure without Bit Fields: ";
cout << sizeof(Loan1) << " Bytes" << endl;
cout << "Size of Structure with Bit Fields: ";
cout << sizeof(Loan2) << " Bytes" << endl;
return 0;
}
OutputSize of Structure without Bit Fields: 12 Bytes
Size of Structure with Bit Fields: 4 Bytes
Explanation
- For the structure 'Loan', the size is 12 bytes which accounts for 4 bytes for each of the three integer members.
- In structure 'Loan2", we have used bit fields to specify the memory allocated to the member variables of a struct in bits.
- We have specified 20 bits for 'principal', 6 bits for 'interest rate', and 6 bits for 'period'.
- They all contributed to 32 bits which is equal to 4 Bytes which is why the size of 'Loan2" is 4 bytes.
Example 2: Class with Bit Fields in C++
In the below example, we have used bit fields with classes instead of struct.
C++
// C++ program to demonstrate the size occupied by a class
// by specifying the bits to member variables of the class
// using bit fields
#include <iostream>
using namespace std;
// Define a class with bit-fields for loan information
class Loan {
public:
// Maximum principal of 1,048,575
unsigned int principal : 20;
// Maximum interest rate of 63
unsigned int interestRate : 6;
// Maximum period of 63 months
unsigned int period : 6;
};
int main()
{
Loan loan1;
loan1.principal = 500000;
loan1.interestRate = 15;
loan1.period = 36;
// Print the size of loan1
// (20+6+6)/8 = 4 Bytes
// 1 Byte = 8 Bits
cout << sizeof(Loan) << " Bytes" << endl;
return 0;
}
Explanation
In the above example, we have used bit fields to specify the memory allocated to the member variables of a class in bits. We have specified 20 bits for 'principal', 6 bits for 'interest rate', and 6 bits for 'period'. They all contributed to 32 bits which is equal to 4 Bytes.
Some Interesting Facts about Bit Fields
1. The number of bits assigned to a member variable can be greater than the default size of the data type of variable.
C++
// C++ program to demonstrate that the number of bits
// assigned to a member variablecan be greater than the
// default size of the data type of variable.
#include <bits/stdc++.h>
using namespace std;
// Define a structure with bit fields
struct values {
int num : 520;
};
int main()
{
values val1;
// Assigning value to num variable
val1.num = 1;
// Print the size of struct
cout << sizeof(val1) << " Bytes" << endl;
return 0;
}
Explanation
The num variable is assigned 520 bits, which (assuming a 32-bit or 4-byte int) would require 16.25 ints or 65 bytes to represent. Rounding up it to the upper limit of 17, 17*32 bits=544 bits would have been enough to store the requested value, but compiler padding and alignment issues push the allotment to 80 bytes i.e. 640 bits or 20 ints.
2. We can not create pointers that point to bit fields because they might not start at a byte boundary.
C++
// C++ program to demonstrate that we can not create
// pointers that points to bit fields
#include <iostream>
using namespace std;
struct BitField {
unsigned int num : 1;
};
int main()
{
BitField var;
var.num = 1;
// Error: Cannot take the address of a bit field
// unsigned
unsigned int* ptr = &var.num;
// Error: Cannot create a reference to a bit field
int& ref = var.num;
cout << var.num << endl;
return 0;
}
Output
./Solution.cpp: In function 'int main()':
./Solution.cpp:15:30: error: attempt to take address of bit-field structure member 'BitField::num'
unsigned int* ptr = &var.num;
^
./Solution.cpp:18:20: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
int& ref = var.num;
^
Applications of Bit Fields in C++
- It is majorly used for memory optimization as it allows us to use only the necessary number of bits to represent a member variable which reduces memory overhead.
- It can be used to compress the data so that it can take less time to transfer data from one point to another over the network.
- It can be used to design hardware registers that have specific bit structures.
- In graphics applications, color components, pixel formats, and image data often have specific bit requirements which can be customized using bit fields.
Similar Reads
Bitmask in C++
In the world of programming, where precision and efficiency are of great importance, bitmasking is a powerful technique that utilizes the manipulation of bits. C++ also offers a platform where programmers can efficiently represent data and unlock unparalleled computational capabilities through bit m
8 min read
CHAR_BIT in C
CHAR_BIT : It is the number of bits in char. These days, almost all architectures use 8 bits per byte (But it is not the case always, some older machines used to have 7-bit byte). It can be found in Let us see an application of it. Suppose we wish to print byte by byte representation of an integer.
1 min read
bitset size() in C++ STL
bitset::size() is a built-in STL in C++ which returns the total number of bits. Syntax: bitset_name.size() Parameter: The function accepts no parameter. Return Value: The function returns an integral value which signifies the number of bits. It eventually returns the size that has been given while i
2 min read
bitset::flip() in C++ STL
bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only. Syntax: bitset_name.flip(int pos) Parameter:
2 min read
bitset none() in C++ STL
bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set. Syntax: bool none() Parameter: The function accepts no parameter. Return Value: The function returns a boolean. The boolean value is True if none of its bits are s
2 min read
Setting Bits in C
In C programming, setting a bit is the process of setting a specific bit of a binary number to 1. This operation is crucial in various applications, including memory management, data processing, and hardware control.In this article, we will learn how to set a bit at a given position in a binary numb
3 min read
Bitwise Operators in C
In C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Bitwise Operators in C++
In C+, Bitwise Operators are the operators that are used to perform bit-level operations on the integers. While performing these operations, integers are considered as sequences of binary digits. These operators are useful for low-level programming, system programming, and optimizing performance.C++
6 min read
Toggling Bits in C++
In C++ programming, toggling a bit involves changing the value of a specific bit in a binary number. This operation is useful in various applications such as cryptography, data compression, and hardware control.In this article, we will explore how to toggle a bit at a given position in a binary numb
4 min read
Bitmasking In C
In this article, we are going to learn about Bitmask in C which is a powerful way to basically work with bits and functions upon boolean logic. It can be used to store data compactly and with much more efficiency in certain cases. What is a Bit? A bit is the smallest unit of data which can either st
4 min read