Chapter - 15: Operations On Bits

The information about colors is to be stored in bits of a char variable called color. The bit number 0 to 6, each represents 7 colors of a rainbow, i.e. bit 0 represents violet, 1 represents indigo, and so on. Write a program that asks the user to enter a number and based on this number it reports which colors in the rainbow does the number represents.


A
Sections
1
Exercises

A

B

1

2

3

4

5

6

7

#include<stdio.h>
#include<conio.h>

#define _BV(x) 1<<x

int main()
{
	unsigned int color, j, k, andmask;
	int i;
	printf("\nEnter the number : ");
	scanf("%u", &color);
	for (i = 0; i <= 6; i++)
	{
		j = i;
		andmask = _BV(j);
		puts("");
		k = color & andmask;
		if (k > 0)
		{
			switch (i)
			{
			case 0:
				printf("Voilet, ");
				break;
			case 1:
				printf("Indigo, ");
				break;
			case 2:
				printf("Blue, ");
				break;
			case 3:
				printf("Green, ");
				break;
			case 4:
				printf("Yellow, ");
				break;
			case 5:
				printf("Orange, ");
				break;
			case 6:
				printf("Red, ");
				break;
			default:
				break;
			}
		}
	}
	_getch();
	return 0;
}

© 2020 Garbage Valuegarbage value logo