Bitwise Operators and Bit fields in C Programming Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Bitwise Operators and Bit fields in C Programming Language

Share This


In this chapter, we will discuss bitwise operators in C language. In the arithmetic logic unit of a processor, operations are performed at the bit-level.

C supports bitwise AND, OR, XOR, complement, left shift, and right shift operations.

In the following program, we have shown the results of different operations on the same data.

#include <stdio.h> int main(void) { int a = 5; // 00000101 int b = 10; // 00001010 printf("& %d \n", (a & b)); printf("| %d \n", (a | b)); printf("^ %d \n", (a ^ b)); printf("~ %d \n", ~a); printf("<<2 %d \n", (a << 3)); printf(">>2 %d \n", (a >> 3)); return 0; }
In the chapter Data Types and Variables, we have discussed that memory allocation is dependent on data types. For an integer variable 4 bytes of memory is allocated. Now if we define a structure Student, in which age and gender variables are declared. We know that the maximum value of age can be less than 120 and instead of storing the gender as 'M' or 'F', we can store it using a bit 0 or 1.
If we define student structure in conventional procedure, it can be defined as below.

typedef struct Student { char name[20]; unsigned int age; unsigned int gen; unsigned int roll; } stud;
Here, memory allocation for a variable of student structure is 32 bytes. This memory allocation can be reduced, if bit fields are used. For age variable, 7 bits are sufficient and for gender representation 1 bit is sufficient. Hence, the structure is redifined as

typedef struct Student { char name[20]; unsigned int age : 7; unsigned int gen : 1; unsigned int roll : 20; } stud;
Here, for one structure variable memory requirement is 24 bytes. A complete code is given below.

#include <stdio.h> typedef struct Student { char name[20]; unsigned int age : 7; unsigned int gen : 1; unsigned int roll : 20; } stud; int main (void) { printf("%d \n", sizeof(int)); printf("%d \n", sizeof(stud)); return 0; }
In the following program, we have shown how to work with standard input and output for bit-fields. Bit-fields can not be used with scanf function directly. Thus the input is taken in one variable and the value is assigned to the corresponding bit-field.

#include <stdio.h> typedef struct Student { char name[20]; unsigned int roll : 20; unsigned int age : 7; unsigned int gen : 1; } stud; int main (void) { int data; stud s; printf("Enter name:"); scanf("%s", s.name); printf("Enter roll:"); scanf("%d", &data); s.roll = data; printf("Enter age:"); scanf("%d", &data); s.age = data; printf("Enter 0 for Male / 1 for Female:"); scanf("%d", &data); s.gen = data; printf("\nName %s\nRoll %d\nAge %d\nGender %d", s.name, s.roll, s.age, s.gen); return 0; }


Happy Exploring!

No comments:

Post a Comment