Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
2.6 kB
4
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;
	unsigned char numInput = 0;
    static int storeVal;
    char commandInput;
    char ch;
    int isValidInput = 1;
    
    printf("%s", intro);
    printf("%s", numInputPrompt);
    
    int digitCount = 0;  // To count the number of digits in the input

    while ((ch = getchar()) != '\n') {
        if (isdigit(ch)) {
            numInput = numInput * 10 + (ch - '0');
            digitCount++;
            if (numInput > 255) {
                isValidInput = 0;
                break;
            }
        } else {
            isValidInput = 0;
            break;
        }
    }

    // Detect if input is just '\n' or non-numeric, or out of range
    if (!isValidInput || digitCount == 0) {
        printf("%s\n", numError);
        return 1; // Exit the program due to invalid input
    }
    
    storeVal = numInput;

    while(exit != 1){
        printf("%s", commandMenu);
        commandInput = getchar();
        fflush(stdin);
        switch(commandInput){
        case 'L':
            storeVal = (storeVal << 1) & 0xFF;
            printf(outputTemplate, storeVal, storeVal);
            getBinary(storeVal);
            break;
        case 'R':
            storeVal >>= 1;
            printf(outputTemplate, storeVal, storeVal);
            getBinary(storeVal);
            break;
        case 'C':
            storeVal = ~storeVal;
            printf(outputTemplate, storeVal, storeVal);
            getBinary(storeVal);
            break;
        case 'E':
            exit = 1;
            break;
        default:
            printf("%s", commandError);
            break;
        }
    }
}

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