Bit Fields In C

Bit Fields In C

Bit-fields allow you to specify the size (in bits) of structure and union members, which can be especially useful when you want to use memory efficiently. They are typically used when you know that the values of certain fields or groups of fields will never exceed a certain limit or are within a small range. Bit-fields help conserve memory, especially when dealing with embedded systems or when you have limited storage available in your program. This feature is valuable for optimizing memory usage in situations where it’s essential to save space.

Declaration of C Bit Fields

Bit fields are variables that are defined using the predefined width or size.

Syntax of C Bit Field

struct
{
    data_type member_name : width_of_bit-field;
};
  1. data_type: This is the data type used to specify the bit-field’s value. It can be an integer type, typically int, signed int, or unsigned int, that determines how the bits in the bit-field are to be interpreted.
  2. member_name: The member name is the identifier that you give to the bit-field, which serves as the name of the bit-field within the structure or union.
  3. width_of_bit-field: This refers to the number of bits allocated to the bit-field. The width must be less than or equal to the bit width of the specified data type (e.g., int). The width determines how many bits the bit-field can use to represent its value.

These three components are essential when defining a bit-field, and they allow you to specify the data type, name, and size (width) of the bit-field within a structure or union.

Applications of C Bit Fields

  1. Limited Storage: Bit-fields are a suitable choice when you have limited memory or storage resources, as they allow you to represent and manipulate data in a compact way, using fewer bits than standard data types.
  2. Device Status and Information: In situations where devices need to transmit status or information encoded as multiple bits, bit-fields are an efficient means of representing this data, optimizing the use of available bits and ensuring efficient communication.
  3. Encryption Routines: Encryption algorithms often work at the bit level to manipulate and transform data. Bit-fields can be a valuable tool in encryption routines to access and manipulate specific bits within a byte, making them useful for bitwise operations and encryption-related tasks.

Example Of C Bit Fields



// C Program to illustrate the structure without bit field
#include <stdio.h>
 
// A simple representation of the date
struct date {
    unsigned int d;
    unsigned int m;
    unsigned int y;
};
 
int main()
{
    // printing size of structure
    printf("Size of date is %lu bytes\n",
           sizeof(struct date));
    struct date dt = { 31, 12, 2014 };
    printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}

Output

Size of date is 12 bytes
Date is 31/12/2014

Structure with Bit Field

The Code given below will define a date with a single member month. The month member will be declared as a bit field with 4 bits.

struct date
{
// month has value between 0 and 15, 
// so 4 bits are sufficient for month variable.
    int month : 4;
};

Same Code With Signed Integers


// C program to demonstrate use of Bit-fields
#include <stdio.h>
 
// Space optimized representation of the date
struct date {
    // d has value between 0 and 31, so 5 bits
    // are sufficient
    int d : 5;
 
    // m has value between 0 and 15, so 4 bits
    // are sufficient
    int m : 4;
 
    int y;
};
 
int main()
{
    printf("Size of date is %lu bytes\n",
           sizeof(struct date));
    struct date dt = { 31, 12, 2014 };
    printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
    return 0;
}

Output

Size of date is 8 bytes
Date is -1/-4/2014
  • When you store a negative value in a signed integer, it is typically represented using two’s complement.
  • Two’s complement involves inverting (flipping) all the bits and then adding 1 to the result to get the binary representation of the negative value.
  • For example, if you have a 5-bit signed integer and store the decimal value 31, it’s represented as 11111 in binary. The most significant bit (MSB) is 1, indicating a negative number. To find the actual value, you perform the two’s complement, which results in 00001, equivalent to -1 in decimal.
  • Similarly, for the value 12 in a 4-bit signed integer, it’s represented as 1100 in binary. The two’s complement yields 0100, which is equivalent to -4 in decimal.

This process of using two’s complement is essential for correctly representing and interpreting negative values in binary form within the constraints of signed integers.

Interesting facts about the C Bit Fields

1. A special unnamed bit field of size 0 is used to force alignment on the next boundary.

// C Program to illustrate the use of forced alignment in
// structure using bit fields
#include <stdio.h>
 
// A structure without forced alignment
struct test1 {
    unsigned int x : 5;
    unsigned int y : 8;
};
 
// A structure with forced alignment
struct test2 {
    unsigned int x : 5;
    unsigned int : 0;
    unsigned int y : 8;
};
 
int main()
{
    printf("Size of test1 is %lu bytes\n",
           sizeof(struct test1));
    printf("Size of test2 is %lu bytes\n",
           sizeof(struct test2));
    return 0;
}

Output

Size of test1 is 4 bytes
Size of test2 is 8 bytes

2.We cannot have pointers to bit field members as they may not start at a byte boundary


// C program to demonstrate that the pointers cannot point
// to bit field members
#include <stdio.h>
struct test {
    unsigned int x : 5;
    unsigned int y : 5;
    unsigned int z;
};
int main()
{
    struct test t;
 
    // Uncommenting the following line will make
    // the program compile and run
    printf("Address of t.x is %p", &t.x);
 
    // The below line works fine as z is not a
    // bit field member
    printf("Address of t.z is %p", &t.z);
    return 0;
}

Output

prog.c: In function 'main':
prog.c:14:1: error: cannot take address of bit-field 'x'
 printf("Address of t.x is %p", &t.x); 
 ^

3. It is implementation-defined to assign an out-of-range value to a bit field member.


// C Program to show what happends when out of range value
// is assigned to bit field member
#include <stdio.h>
 
struct test {
    // Bit-field member x with 2 bits
    unsigned int x : 2;
    // Bit-field member y with 2 bits
    unsigned int y : 2;
    // Bit-field member z with 2 bits
    unsigned int z : 2;
};
 
int main()
{
    // Declare a variable t of type struct test
    struct test t;
    // Assign the value 5 to x (2 bits)
    t.x = 5;
 
    // Print the value of x
    printf("%d", t.x);
 
    return 0;
}

Output

Implementation-Dependent

4. Array of bit fields is not allowed


// C Program to illustrate that we cannot have array bit
// field members
#include <stdio.h>
 
// structure with array bit field
struct test {
    unsigned int x[10] : 5;
};
 
int main() {}

Output

prog.c:3:1: error: bit-field 'x' has invalid type
 unsigned int x[10]: 5;
 ^

FAQ- Bit Fields In C

Q1. What are bit fields in C?

Ans. In C, in addition to declarators for members of a structure or union, a structure declarator can be defined as a specified number of bits, creating what’s known as a “bit field.” The length of the bit field is specified by the number of bits and is separated from the declarator for the field name by a colon (:). A bit field is interpreted as an integral type and allows you to represent and manipulate data as a specific number of bits, which can be especially useful for memory-efficient data storage and manipulation.

Q2. Why use bit fields in C?

Ans. Bit fields in C are significant for three key reasons:
They reduce memory usage.
They are easy to implement.
They provide code flexibility.

Q3. What is the size of bits in C?

Ans. char is a minimum of 8 bits.
short and int have a minimum size of 16 bits.
long is at least 32 bits.
long long must contain a minimum of 64 bits.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment