logoISU  

CS456 - Systems Programming

Spring 2025

Displaying ./code/forkExec/nextPowerof2.c

//next power of 2
// Ex: if I give it 9, it will out put 16, 24 will output 32 etc.
//
// 0000 1001 : 9  input
// 0001 0000 : 16 output
//

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

int checkBit(int n, int bit);
int setBit(int n, int bit);

int main(int argc, char **argv){

	//user did not provide number
	if(argc < 2){
		fprintf(stderr, "Usage %s number\n", argv[0]);
		exit(1);
	}

	int num;

	//use atoi to convert to integer because every command line arg is a string. 
	num = atoi(argv[1]);

	//number should be positive
	if (num <= 0){
		fprintf(stderr, "Enter a positive number\n");
		exit(1);
	}

	int next = 0;
	for(int i=31; i > 0; i--){
		if(checkBit(num, i)){
			next = setBit(next, i+1);
			break;
		}		
	}	

	printf("%d\n", next);
	return 0;

}

int checkBit(int n, int bit){

	if(n & (1 << bit)) 
		return 1;
	else
		return 0;
}

int setBit(int n, int bit){

	return (n | (1 << bit));

}