Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.7 kB
2
Indexable
Never
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define ZERO '0'
#define ONE '1'
#define SPACE ' '

typedef char* string;

void getBinary(int a);

int main(){
	string intro = "Bit Handling Operations\n";
	string numInputPrompt = "Please input an integer (0-255): ";
	string commandMenu = "\n--------------------------\n"
						"Operations\n--------------------------\n"
						"L: Left-shift\nR: Right-shift\nC: Complement\n"
						"E: End program\n--------------------------\n"
						"Please select operation: ";
	string outputTemplate = "Decimal: %d, Hexadecimal: %X; Binary: ";
	string numError = "Not numeric or out of range!";
	string commandError = "Invalid selection!\n";
	int exit = 0;
	int numInput;
	static int storeVal;
	char commandInput;
	
	printf(intro);
	printf(numInputPrompt);
	scanf("%d",&numInput);
	fflush(stdin);
	storeVal = numInput;

	if (numInput >= 0 && numInput <= 255) {
		while(exit != 1){
			printf(commandMenu);
			commandInput = getchar();
			fflush(stdin);
			switch(commandInput){
			case 'L':
				storeVal <<= 1;
				printf(outputTemplate, storeVal, storeVal);
				getBinary(storeVal);
				break;
			case 'R':
				storeVal >>= 1;
				printf(outputTemplate, storeVal, storeVal);
				getBinary(storeVal);
				break;
			case 'C':
				printf("Complement\n");
				break;
			case 'E':
				exit = 1;
				break;
			default:
				printf("Invalid\n");
				break;
			}
		}	
	}
	else {
		printf(numError);
	}
}

void getBinary(int a){
	int n = 8;
	int mask = 1 << (n-1);
 
	int i;
	for (i=1; i<=n; i++){
		putchar (a & mask ? ONE : ZERO);
		a <<= 1;
	}	
}
Leave a Comment