In: Computer Science
using C language
Create a bitwise calculator that ask user for input two input, first int, bitwise operation, second int (i.e 5 & 9)
only those bitwise operation are allowed: & ~ ^ | << >>. If user uses wrong operators stop program and ask again.
Convert the first int and second int into 8 BITS binary (00000000) and use bitwise operator given by user to either AND, OR, XOR, etc (ie 1001 & 1111)
#include <stdio.h> #define bits 8 int main(void) { // declare variables int a, b; char op; int binA[bits] = {0, 0, 0, 0, 0, 0, 0, 0}; int binB[bits] = {0, 0, 0, 0, 0, 0, 0, 0}; int res[bits]; int i = bits - 1; int temp; // read numbers printf("Enter first operand: "); scanf("%d", &a); printf("Enter second operand: "); scanf("%d", &b); // read operator printf("Enter operation (&, ~, ^, |, <<, >>) (enter < for << and > for >>): "); scanf(" %c", &op); // operator validation while (op != '&' && op != '~' && op != '^' && op != '<' && op != '>' && op != '|') { printf("Invalid operation!!"); printf("\nEnter operation (&, ~, ^, |, <<, >>) (enter < for << and > for >>): "); scanf("%c", &op); } // converting first number to binary temp = a; while (temp > 0) { binA[i] = temp % 2; temp = temp / 2; i--; } // converting second number to binary i = bits - 1; temp = b; while (temp > 0) { binB[i] = temp % 2; temp = temp / 2; i--; } // display the bits printf("\n%d in %d-bits binary = ", a, bits); for(i = 0; i < bits; i++) { printf("%d", binA[i]); } printf("\n%d in %d-bits binary = ", b, bits); for(i = 0; i < bits; i++) { printf("%d", binB[i]); } // apply the operation accordingly // and store the result in the res array if (op == '&') { for (i = 0; i < bits; i++) { res[i] = binA[i] & binB[i]; } } else if (op == '^') { for (i = 0; i < bits; i++) { res[i] = binA[i] ^ binB[i]; } } else if (op == '|') { for (i = 0; i < bits; i++) { res[i] = binA[i] | binB[i]; } } else if (op == '<') { for (i = 0; i < bits; i++) { res[i] = binA[i] << binB[i]; } } else if (op == '>') { for (i = 0; i < bits; i++) { res[i] = binA[i] >> binB[i]; } } else { for (i = 0; i < bits; i++) { if (binA[i] == 1) { binA[i] = 0; } else { binA[i] = 1; } if (binB[i] == 1) { binB[i] = 0; } else { binB[i] = 1; } } } // display result // if operation is ~ we display both numbres after applying ~ opertaion if (op == '~') { printf("\n\nResult\n"); printf("~%d = ", a); for (i = 0; i < bits; i++) { printf("%d", binA[i]); } printf("\n~%d = ", b); for (i = 0; i < bits; i++) { printf("%d", binB[i]); } } else if (op == '<') { printf("\n\nResult\n"); printf("%d << %d = ", a, b); for (i = 0; i < bits; i++) { printf("%d", res[i]); } } else if (op == '>') { printf("\n\nResult\n"); printf("%d >> %d = ", a, b); for (i = 0; i < bits; i++) { printf("%d", res[i]); } } // else display the result else { printf("\n\nResult\n"); printf("%d %c %d = ", a, op, b); for (i = 0; i < bits; i++) { printf("%d", res[i]); } } return 0; }
FOR HELP PLEASE COMMENT.
THANK YOU