C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Programming Tips & Tricks » C - Tips & Tricks

How can we use a single byte to store 8 values in C?

By: IncludeHelp, on 26 JAN 2017

This is a C and C++ programming code optimization tip. Here we will learn to use a single byte variable to store 8 different values, but values must be either true or false i.e. 0 or 1.

Where this optimization method can be used?

Whenever, we have flag type values, which are either true (1) or false (0), then we can store them in 8 bits separately, as we all know that a byte has 8 bits and we can use them to store 8 flag values.

Let suppose there is an input field in program, "do you have passport?" the answer will be either true (1) or false (0).

How to use?

Declare an unsigned character type variable (since signed char has 7 bits because last bit is used to defined sign).

unsigned char flags=0;

Fix the bit positions for different values (count from 0 to 7), here we are going to store 3 different values.






bit 0) Marital status
bit 1) Passport status
bit 2) Disability status

flags |= 0x01;	//set bit 0
flags |= 0x02;	//set bit 1
flags |= 0x04;	//set bit 2

Now, let confirm by checking the values

if(flags & 0x01)
	printf("Marital status: true\n");
else
	printf("Marital status: false\n");
if(flags & 0x02)
	printf("Passport status: true\n");
else
	printf("Passport status: false\n");	
if(flags & 0x04)
	printf("Disability status: true\n");
else
	printf("Disability status: false\n");

How to clear a particular bit?

flags &= ~0x02;

Here, passport status will be false.

How to clear all bits?

flags =0;

This statement will clear all bits.

Values that are used to check particular bit


bit 0		0x01
bit 1		0x02
bit 2		0x04
bit 3		0x08
bit 4		0x10
bit 5		0x20
bit 6		0x40
bit 7		0x80    

Here is the program

#include <stdio.h>
int main()
{
	unsigned char flags=0;
	flags |=0x01;
	flags |=0x02;
	flags |=0x04;
	
	if(flags & 0x01)
		printf("Marital status: true\n");
	else
		printf("Marital status: false\n");
	if(flags & 0x02)
		printf("Passport status: true\n");
	else
		printf("Passport status: false\n");	
	if(flags & 0x04)
		printf("Disability status: true\n");
	else
		printf("Disability status: false\n");	
	
	flags &= ~0x02;
	if(flags & 0x01)
		printf("Marital status: true\n");
	else
		printf("Marital status: false\n");
	if(flags & 0x02)
		printf("Passport status: true\n");
	else
		printf("Passport status: false\n");	
	if(flags & 0x04)
		printf("Disability status: true\n");
	else
		printf("Disability status: false\n");		
	
	return 0;
}

Output

    Marital status: true
    Passport status: true 
    Disability status: true 
    Marital status: true
    Passport status: false
    Disability status: true

COMMENTS