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

If you are here first time, I would recommend to read Bitwise Operators - Find output programs (set -1) first.

This is a second set of 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=0xFA;
	
	a= (a>>4) | (a<<4);
	
	printf("a = %02X\n",a);
				
	return 0;
}

Output

a= AF

Explanation

The expression a= (a>>4) | (a<<4); will swap the nibbles, here a>>4 will shift the last 4 bits (from 7 to 4) to the first 4 position (3 to 0) and statement a<<4 will shift the first 4 bits from (0 to 3), to the last 4 position (from 4 to 7). And the Bitwise OR ('|') operator will add both of the nibbles, thus the output will be AF (swapped nibbles).


Program - 2

#include <stdio.h>
int main()
{
	unsigned char a=0xFA;
	char loop;
	
	for(loop=7; loop>=0; loop--)
		printf("%d ",(a & (1<<loop))?1:0);
	
	printf("\n");
	
	return 0;
}

Output

1 1 1 1 1 0 1 0

Explanation

This program is to get BINARY value of any 8 bits integer number, expression (a & (1<<loop))?1:0 will check whether particular bit is set (high) or not, if it is set (high), '1' will print else '0' will print.


Program - 3

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

Output

FF

Explanation

Bitwise XOR (^) returns 1, if one operand's bit is 1 and other operand's bit is 0, consider the given truth table:

a	b	a^b
0	0	0
0	1	1
1	0	1
1	1	0

Expression (a^b)
a:	0xAA		1010 1010
b:	0x55		0101 0101
(a^b)	0xFF		1111 1111

Thus, the output will be "FF".


Program - 4

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

Output

a= AA

Explanation

When, some value is XORed with a number twice, same (initial value) returns.
Consider the expression evaluation, first (a= a^0x55)
a: 0xAA - 1010 1010
0x55 - 0101 0101
(a^0x55) - 1111 1111 = 0xFF

Now, second expression (a= a^0x55)
a: 0xFF - 1111 1111
0x55 - 0101 0101
(a^0x55) - 1010 1010 = 0x55
Thus, the output will be "AA".






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.