"use strict";
/**
* Prints the binary representation of a single character.
*
* @param {string} char - A single character.
* @returns {string} The 8-bit binary representation.
* @throws {Error} If the input is not a single character.
*/
function charToBits(char) {
if (typeof char !== "string" || char.length !== 1) {
throw new Error("Input must be exactly one character.");
}
// Get the Unicode code point for the character.
const code = char.charCodeAt(0);
// Convert to binary and pad to at least 8 bits.
return code.toString(2).padStart(8, "0");
}
/**
* Prints a character and its binary representation.
*
* @param {string} char - A single character.
*/
function printCharacterBits(char) {
const bits = charToBits(char);
console.log(`Character: '${char}'`);
console.log(`Decimal : ${char.charCodeAt(0)}`);
console.log(`Binary : ${bits}`);
}
// -----------------------------------------------------------------------------
// Usage examples
// -----------------------------------------------------------------------------
try {
printCharacterBits("A");
console.log();
printCharacterBits("a");
console.log();
printCharacterBits("5");
} catch (error) {
console.error(`Error: ${error.message}`);
}
/*
run:
Character: 'A'
Decimal : 65
Binary : 01000001
Character: 'a'
Decimal : 97
Binary : 01100001
Character: '5'
Decimal : 53
Binary : 00110101
*/