This repository was archived by the owner on Jul 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.js
More file actions
64 lines (50 loc) · 1.7 KB
/
Copy pathbinary.js
File metadata and controls
64 lines (50 loc) · 1.7 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
#!/usr/bin/env node
const readline = require("node:readline/promises");
const { stdin: input, stdout: output } = require("node:process");
const c = {
reset: "\x1b[0m",
cyan: "\x1b[36m",
green: "\x1b[32m",
yellow: "\x1b[33m",
red: "\x1b[31m",
bold: "\x1b[1m",
};
function textToBinary(text) {
return Array.from(text, (ch) => ch.charCodeAt(0).toString(2).padStart(8, "0")).join(" ");
}
function binaryToText(binary) {
const chunks = binary.trim().split(/\s+/);
if (chunks.length === 1 && /^[01]+$/.test(chunks[0]) && chunks[0].length % 8 === 0) {
chunks[0] = chunks[0].match(/.{8}/g).join(" ");
}
const normalizedChunks = chunks.join(" ").split(" ");
for (const chunk of normalizedChunks) {
if (!/^[01]{8}$/.test(chunk)) {
throw new Error("Binary input must contain 8-bit groups made of 0s and 1s.");
}
}
return normalizedChunks.map((chunk) => String.fromCharCode(Number.parseInt(chunk, 2))).join("");
}
async function main() {
const rl = readline.createInterface({ input, output });
try {
console.log(`${c.bold}${c.cyan}Binary${c.reset}`);
const mode = (await rl.question(`${c.yellow}Please choose a mode (E = Encode, D = Decode) - ${c.reset}`))
.trim()
.toLowerCase();
const text = await rl.question(`${c.yellow}Input - ${c.reset}`);
if (!["e", "encode", "d", "decode"].includes(mode)) {
throw new Error("Invalid mode. Use E or D.");
}
const result = mode.startsWith("e")
? textToBinary(text)
: binaryToText(text);
console.log(`${c.green}Result -${c.reset} ${result}`);
} catch (err) {
console.error(`${c.red}Error -${c.reset} ${err.message}`);
process.exitCode = 1;
} finally {
rl.close();
}
}
main();