Program description:

Lab 4

Write a C program to run on ocelot which will flip a single bit in a number entered by the user using the binary representation of the number. The user should input the original integer value between 1 and 1000 inclusive using a scanf. Output is to the screen. You must use a bitwise operator for this program.
For this assignment give the user directions asking them to enter the integer and then ask them which bit to flip. That can be a number between 0 and 31. Prompt the user for what should be entered each time. After completing the operation ask the user if they want to do another operation again. The user would enter Y or y to do it again. You do not need to use getopt for this program.
If the user enters a 1 as the initial value and a 0 for the bit to switch the result would be 0. If the user enters a 10 as the initial value and a 1 for the bit to switch then the result would be 8. . If the user enters a 10 as the initial value and a 2 for the bit to switch then the result would be 14.

Your code:

Make file

bitswitch: bitswitch.c
	gcc -o bitswitch bitswitch.c -I.
clean:
	rm *.o *.err

.c File

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

#define FLUSH while(getchar() != '\n')

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

	int bitToSwitch;
	uint32_t input, result, mask;
	char tryAgain = 'y';
	
	while(tryAgain == 'y' || tryAgain == 'Y'){ //loop to repeat process
		
		//initialization
		mask = 1; 
		result = 0;

		//gets starting value
		printf("Please enter an integer value between 1 and 1000 to start with.\n");
		scanf("%d", &input); 

		//checks if starting value is between 1 and 1000
		if(input < 1 || input > 1000){
		
			printf("Input value not between 1 and 1000.\n");
			exit(100);
		}

		//gets bit to switch
		printf("Which bit would you like to switch? Please enter a number between 0 and 31.\n");

		scanf("%d", &bitToSwitch);

		//checks if bit to switch is between 0 and 31
		if(bitToSwitch < 0 || bitToSwitch > 31){
			
			printf("The bit you would like to switch does not exist.\n");
			exit(100);	
		}
		
		mask = mask << (bitToSwitch); //shifts mask to desired position to switch the bit
		result = input ^ mask; //Uses xor to switch the desired bit in the starting value
		
		printf("Result: %d\n", result); //prints result

		//asks user if they would like to repeat and gets answer
		printf("Would you like to try again? Y/N\n");
		FLUSH;
		tryAgain = getchar();
	}

	exit(0);	
}

All the assignments will be posted. Subscribe for more! :)