-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_calculator.js
More file actions
68 lines (59 loc) · 2.14 KB
/
Copy pathbinary_calculator.js
File metadata and controls
68 lines (59 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Function to append a value to the input field
function appendValue(value) {
document.getElementById('binaryInput').value += value;
}
// Function to clear the input field
function clearInput() {
document.getElementById('binaryInput').value = '';
}
// Function to perform arithmetic operation (+, -, *, /)
function performOperation(operator) {
let input = document.getElementById('binaryInput').value;
if (input === '') return; // If no input, do nothing
// Validate that input contains only 0s and 1s (binary digits)
if (!/^[01]+$/.test(input)) {
alert('Invalid binary number!');
clearInput();
return;
}
// Store the operator and clear the input field
sessionStorage.setItem('operator', operator);
clearInput();
}
// Function to calculate the result based on the stored operator
function calculate() {
let input = document.getElementById('binaryInput').value;
let storedOperator = sessionStorage.getItem('operator');
if (!storedOperator || input === '') return; // If no stored operator or no input, do nothing
// Validate that input contains only 0s and 1s (binary digits)
if (!/^[01]+$/.test(input)) {
alert('Invalid binary number!');
clearInput();
return;
}
let result;
let num1 = parseInt(input, 2); // Convert binary input to decimal
let num2 = parseInt(sessionStorage.getItem('previousInput'), 2); // Convert previous binary input to decimal
switch (storedOperator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num1 === 0) {
alert('Division by zero error!');
clearInput();
return;
}
result = num2 / num1;
break;
}
// Display the result in binary format
document.getElementById('result').value = result.toString(2);
sessionStorage.setItem('previousInput', result.toString(2));
}