logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul19/powerOf2.c

/*

this program finds the biggest power of two smaller than
the given number


*/

#include <stdio.h>
#include <stdlib.h>

int isPowerOf2(int x);
int biggestPowerOf2(int x);
int setBit(int n, int bit);

int main(int argc, char *argv[]){
	
	if(argc < 2){
		fprintf(stderr, "Usage %s <number>\n", argv[0]);
		exit(1);
	}

	int a, pwr2;

	a = atoi(argv[1]);

	if(a < 0){
		printf("Enter a positive number\n");
		exit(1);
	}

	if(isPowerOf2(a) == 1){
		printf("%d is a power of 2\n", a);
	} else {
	pwr2 = biggestPowerOf2(a);
	printf("Largest power of 2 smaller than %d is %d\n", a, pwr2);	
	}




	return 0;
}
int isPowerOf2(int x){

	int bit, count = 0;

	for(int i = 31; i >= 0; i--){
		bit = (x >> i) & 1;
		if(bit == 1)
			count++;

		if(count > 1)
			return 0;
	}

	return 1;

}

int biggestPowerOf2(int x){

	int bit, p = 0;
	//ints are 32 bits, 
	//starting with leftmost bity (bit 31) and going all the way to bit 0
	for (int i = 31; i >= 0; i--){
		bit = (x >> i) & 1; //right-shifting given number i times and ANDing it with 1
		if(bit == 1){ //if the bit is 1
			p = setBit(p, i); //set the i'th bit of p and exit the loop
			break;
		}	

	} 
	return p;		
}

int setBit(int n, int bit){

	return n | 1 << bit;

}