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

Home » C programming language

Bitwise Operators - Find output programs in C with explanation (Set 1)

This section contains find output programs on C language Bitwise Operators; each question has correct output and explanation about the answer.

Predict the output of following programs.

Program - 1

#include <stdio.h>
int main()
{
	unsigned char a=0xAA;
	unsigned char b=0;
	
	b= (a&0x0F);
	
	printf("b= %02X\n",b);
	
	return 0;
}

Output

b= 0A

Explanation

In the statement (a&0x0F) bit masking is applying on the a, it will return first 4 bits (from 0 to 3) of the a, thus the output will be 0A [in Binary 0000 1010].


Program - 2

#include <stdio.h>
int main()
{
	unsigned char a=0xAA;
	
	if(a & 0x01)
		printf("one - true\n");
	else
		printf("one - false\n");
		
	if(a & 0x02)
		printf("two - true\n");
	else
		printf("two - false\n");
				
	return 0;
}

Output

one - false
two - true

Explanation

Bitwise AND '&' returns true if specified bit is set (high), here binary value of a will be (1010 1010), thus, statement (a & 0x01) will return false, because first bit of the a is low (0) and the statement (a & 0x02) will return true because second bit of the a is set (1).


Program - 3

#include <stdio.h>
int main()
{
	unsigned char a=0xAA;
	
	printf("a= %02X\n",a);
	
	if(a | 0x01)
		printf("true\n");
	else
		printf("false\n");
	
				
	return 0;
}

Output

a= AA
true

Explanation

Bitwise OR '|' operator returns true, if any bit (from both operands, on specific position) is set (1)/high. In the statement (a | 0x01) [ in Binary: 1010 1010 & 0000 0001] first bit of second operand is true, thus, this statement will return 1 and condition will be true.


Program - 4

#include <stdio.h>
int main()
{
	unsigned char a=0x00;
	
	a= a|0x01;
	a= a|0x02;
	a= a|0x04;
	a= a|0x08;
	
	printf("a= %02X\n",a);
				
	return 0;
}

Output

a= 0F

Explanation

Here, bitwise OR operator will add the particular bit by 1.
a= a|0x01; [Here, bit [0] will be 1 (because it was 0).
a= a|0x02; [Here, bit [1] will be 1 (because it was 0).
a= a|0x04; [Here, bit [2] will be 1 (because it was 0).
a= a|0x08; [Here, bit [3] will be 1 (because it was 0).
Thus, the final output will be '0F' (all four bits from 0 to 3 are set now).


Program - 5

#include <stdio.h>
int main()
{
	unsigned char a=0x00;
	
	a = ~a;
	
	printf("a= %02X\n",a);
				
	return 0;
}

Output

a= FF

Explanation

Bitwise NOT/ Negation/ One's compliment operator (~) reverses the bit(s) from 0 to 1 and 1 to 0, in this program value of a is 0x00 (in Binary: 0000 0000), statement a = ~a will reverse all the bits and assigned them into variable a again, then, the value of a will be 0xFF [in Binary: 1111 1111].







Want more exercise on C language Bitwise Operators - Find output of C programs.


ANY DOUBT? WRITE HERE...