logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul14/bitwise.c

/*

Demonstrating Bitwise operations

C supports 6 bitwise operations

& - bitwise AND
| - bitwise OR
^ - bitwise XOR
~ - bitwise NOT
<< - left shift
>> - right shift

*/


#include <stdio.h>

int main(){

	unsigned int a = 60; //60 in binary 0011 1100
	unsigned int b = 13; //13 in binary 0000 1101
	int c = 0; //notice that c is not unsigned, unlike a or b.

	//AND Operation
	//both cooresponding bits are 1
	c = a & b;
	// 60 - 0011 1100
	// 13 - 0000 1101
	//      0000 1100 = 12
	printf("%d & %d = %d\n", a, b, c);

	//OR Operation
	//at least one of the cooresponding bits is a 1
	c = a | b;
	// 60 - 0011 1100
	// 13 - 0000 1101
	//      0011 1101 = 61
	printf("%d | %d = %d\n", a, b, c);

	//XOR Operation
	//the cooresponding bits are different
	c = a ^ b;
	// 60 - 0011 1100
	// 13 - 0000 1101
	//      0011 0001 = 49
	printf("%d ^ %d = %d\n", a, b, c);

	//NOT Operation (notice that NOT only requires one argument)
	//1 bits become 0 bits , 0 bits become 1
	c = ~a;
	//60 - 0011 1100
	//~60- 1100 0011 = -61
	printf("60 with bits flipped is %d\n", c);
	
	//left shift operator
	// the bits are shifted to the left a specified number of times
	// 0 bits are then added to the right end, leftmost bit drops out
	// a left shift of 1 bit is equivalent to multiplying by 2 
	c = a << 1;
	//60 - 0011 1100
    //     0111 1000 = 120
    printf("%d left shift 1 = %d\n", a, c);

    //right shift operator
    //the bits are shifted to the right a specified number of times
    //0 bits are added to the left end, rightmost bits drop out
    //a right shift of 1 is equivalent to dividing by 2.
	c = a >> 1;
	//60 - 0011 1100
    //     0001 1110 = 30
    printf("%d right shift 1 = %d\n", a, c);



	return 0;
}