logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul15/bitoper.c

/*

Demonstrating bit operations

Given a number N, we want to do something to the Kth bit of this number.

Setting  a bit - if Kth bit is 0, change it to 1. if bit is 1 leave it alone.
Clearing a bit - if Kth bit is 1, change to 0. if bit is 0, leave it unchanged.
Toggling a bit - if Kth bit is 1, change to 0. if bit is 0, change it to 1.


*/

#include <stdio.h>


void printBinaryNum(int num, int numBits);

//all three of these functions take in the same arguments, the number, 
//and the bit we're dealing with
int setBit(int n, int bit);  // uses bitwise OR
int clearBit(int n, int bit); // uses a combination of the biwise AND and NOT operations
int toggleBit(int n, int bit); //uses bitwise XOR

int main(){

	int a = 45;

	printf("%d\n", a);
	printBinaryNum(a, 8);

	int b = setBit(a, 1);

	printf("%d\n", b);
	printBinaryNum(b, 8);

	int c = clearBit(a, 0);
	printf("%d\n", c);
	printBinaryNum(c, 8);

	int d = toggleBit(a, 2);
	printf("%d\n",d);
	printBinaryNum(d, 8);

	return 0;
}

// 45 0010 1101
//printing the binary number (from binary.c)
void printBinaryNum(int num, int numBits){

	int bit;

	for(int i = numBits -1; i >= 0; i--){
		bit = (num >> i) & 1;
		if(bit == 1)
			putchar('1');
		else
			putchar('0');
	}

	printf("\n");

}
/*

These are slightly different from how geeksforgeeks did the bitwise manipulations

I call the rightmost bit bit 0, while they treated the rightmost bit as bit 1.
Otherwise, they work the same way.

*/
int setBit(int n, int bit){

	return n | 1 << bit;

}

int clearBit(int n, int bit){

	return n & ~ (1 << bit);
}

int toggleBit(int n, int bit){

	return n ^ 1 << bit;
}