C Programming

BIT OPERATIONS
C has the advantage of direct bit manipulation and the operations available are,

OperationOperatorComment Value of Sum beforeValue of sum after
AND&sum = sum & 2; 40
OR|sum = sum | 2; 46
Exclusive OR^sum = sum ^ 2; 46
1's Complement~sum = ~sum; 4-5
Left Shift<<sum = sum << 2; 416
Right Shift>>sum = sum >> 2; 41



	/* Example program illustrating << and >> */
	#include <stdio.h>

	main()
	{
		int  n1 = 10, n2 = 20, i = 0;
		
		i = n2 << 4;  /* n2 shifted left four times */
		printf("%d\n", i);
		i = n1 >> 5;  /* n1 shifted right five times */
		printf("%d\n", i);
	}

	Sample Program Output
	320
	0


/* Example program using EOR operator */ #include <stdio.h> main() { int value1 = 2, value2 = 4; value1 ^= value2; value2 ^= value1; value1 ^= value2; printf("Value1 = %d, Value2 = %d\n", value1, value2); }
Sample Program Output Value1 = 4, Value2 = 2
/* Example program using AND operator */ #include <stdio.h> main() { int loop; for( loop = 'a'; loop <= 'f'; loop++ ) printf("Loop = %c, AND 0xdf = %c\n", loop, loop & 0xdf); }
Sample Program Output Loop = a, AND 0xdf = A Loop = b, AND 0xdf = B Loop = c, AND 0xdf = C Loop = d, AND 0xdf = D Loop = e, AND 0xdf = E Loop = f, AND 0xdf = F


© Copyright B Brown. 1984-1999. All rights reserved.