×

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall within a certain range and not exceed a certain threshold.

Example:

#include<stdio.h>
         //presentation of data done
         struct date {
//declaring variables
             unsigned int d;
                unsigned int m;
                unsigned int y;
        };
        int main ()
        {
printf (“size of date is %lu bytes \n”,  //printing the statement 
                              Size of (struct date));
               struct date dt = {31, 12,2014};
printf (“Date is %d%d%d”, dt. d, dt.m, dt.y);
         }

Output:

Bit Fields in C

From the above code, we know that the date takes 12 bytes but as we know 4 bytes is taken by unsigned int and we also know date is always from the values 1 to 31 and month is 1 to 12.

Example using signed integers

#include<stdio.h>
//space develop for presentation of date
struct date {
              // d taking values between the range of 0 to 31 bytes, 5 bits
              int d:5;
       // m takes Values between 0 to 12, so 4 bits
              int m:4;
              int y;
   };
         int main ()
{ 
printf (“date size is %lu bytes \n”, size of (struct date));
              struct date dt = {31,12,2014};
printf (“date is %d%d%d”, dt. ,dt.m, dt. y);
               return 0;
           }

Output:

Bit Fields in C

From the above result, we can see that the value obtained is negative because as 31 is equals to 11111 as it is stored in 5-bit signed integer and the most significant bit is 1, to obtain its original value we should calculate it by 2’s compliment, after calculating we obtain 00001 which is equals to decimal number 1 so as the number is negative it shows -1. Similarly, it happens with 12 equals to 1100 stored in 4-bit Signed int by calculating with 2’s compliment we get -4.

Amazing facts related to bit fields in C

  • To force alignment special unnamed of bit field, size 0 is used on another boundary

Example:

#include<stdio.h>
      //presentation of structure without an alignment force
      struct test1 {
unsigned int x: 5;
              unsigned int y:8;
       };
       //presentation of structure with an alignment force
       struct test2 {
               unsigned int x:5;
               unsigned int:0;
                unsigned int y: 8;
         };
         int main ()
         {
printf(“size of test1 is %lu bytes\n”, size of (struct test 1));
printf (“size of test2 is %lu bytes\n”, size of (struct test 2));
                 return 0;
           }

Output:

Bit Fields in C
  • As they do not start at byte boundary,we may not have pointers to bit field members:

Example:

#include<stdio.h>
            struct test {
                   unsigned int x:5;
                   unsigned int y:5;
unsigned int z;
 };
             int main ()
             {
                   struct test t;
//Leaving a line uncommented causes the programme to build and run.
printf (“address of t.x is %p”, &t.x);


                  //as z is not a member of bit field so below line works fine
printf (“address of t.z is %p”, &t. z);
                    return 0;
              }

Output:

Bit Fields in C

Bit field declaration

 Structure of the bit field declaration:

struct {
          type [member name] : width;
};

The below table shows the variable elements of bit field:

Sr. NoElements & Description
   1.Type: An int type that determines how bit fields clarify and the type may be unsigned or singed int.
2.Member _ name: Bit field name
3.Width: The bit width of specified type must be greater than or equal to Width and the width are bits number in bit field

Bit fields can be defined as variables with predefined width, and it can hold more than one bit.

Example: For storing values from 0 to 7 variable is needed and we should define bit field with width 3

struct {
            unsigned int age: 3;
       } Age;

If we use more than 3 bits, then it will not be allowed.

Example:

#include<stdio.h>
         #include<string.h>
         struct {
               unsigned int age: 3;
          } Age;
         int main () {
Age. Age=4;
printf (“size of (Age): %d\n”, size of (Age));
printf (“Age. age: %d\n”, Age. age);
Age.age=7;
printf (“Age. age: %d\n”, Age. age);
Age.age =8;
printf (“Age. age: %d\n”, Age. age);
return 0;
}

Output:

Bit Fields in C

Related Topics

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Types of Function in C

A function is a piece of code that accomplish a certain operation for a specific task. There are two types of functions in C: System-defined function (Library Function)User-defined function 1. System defined Function...

8 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

Data Types in C

Data type is a very important concept in C programming language. Simply, “A data type is the classification of data values that a data item can have.” We need to...

11 minutes read.

Infinite loop in C

Definition of infinite loop The infinite loop is a loop that does not get dismissed because of its looping construct. A continuous output or no output are the two possible outcomes...

3 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.

How to find square root in C Language

Before understanding the square root program in C language, one must know about the square root of a number. A square root is a mathematical term. The square root of a...

5 minutes read.

Example of Iteration in C

The iterations in the C language are the statements which are executed number of times until a certain condition is reached. These iterations are regarded as “Loops” in C language....

3 minutes read.

Multiplication table program in C using For loop

Before we move on the program of multiplication table of any natural number, first we have to know about the For loop statement. The syntax of ‘for’ loop in C programming...

3 minutes read.

C Pointers

Pointers in C A pointer is a variable, which contains the address of another variable, i.e., it’s a variable which has the address of another variable as its value. The utilization...

4 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

How to return a Pointer from a Function in C?

In the C programming language, pointers are variables that hold the address memory location of another variable. We could also input pointers to a function and return pointers from a...

3 minutes read.

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within...

3 minutes read.

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is...

3 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

C Program to Find the Largest Number using Ternary Operator

In this tutorial, we will write some program to determine which of the provided integers is larger using the ternary operator, also known as the conditional operator in C. Ternary Operator: The ternary...

3 minutes read.

C Program for Extended Euclidean algorithms

The Euclidean method simply computes the GCD (greatest common divisor) of two numbers, p and q. (Let's assume) The GCD of two integers is the greatest number that divides them both....

3 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

Purpose of a Function Prototype in C

A function prototype in C is a declaration of a function that specifies the function's name, return type and parameters. It has the following syntax: return_type function_name(parameter_list); For example, the prototype for...

4 minutes read.