How to print the bits of a character in TypeScript

1 Answer

0 votes
/**
 * Converts a single character to its 8-bit binary representation.
 *
 * @param char A single character.
 * @returns An 8-bit binary string.
 * @throws Error If the input is not exactly one character.
 */
function charToBits(char: string): string {
    if (char.length !== 1) {
        throw new Error("Input must be exactly one character.");
    }

    const codePoint: number = char.charCodeAt(0);
    const binaryString: string = codePoint.toString(2).padStart(8, "0");

    return binaryString;
}

/**
 * Prints a character and its binary representation.
 *
 * @param char A single character.
 */
function printCharacterBits(char: string): void {
    const bits: string = charToBits(char);
    const decimalValue: number = char.charCodeAt(0);

    console.log(`Character: '${char}'`);
    console.log(`Decimal  : ${decimalValue}`);
    console.log(`Binary   : ${bits}`);
}

/**
 * Prints each bit separately.
 *
 * @param char A single character.
 */
function printBitsIndividually(char: string): void {
    const bits: string = charToBits(char);

    process.stdout.write(`Bits for '${char}': `);

    for (const bit: string of bits) {
        process.stdout.write(`${bit} `);
    }

    process.stdout.write("\n");
}

// -----------------------------------------------------------------------------
// Usage examples
// -----------------------------------------------------------------------------

try {
    const character1: string = "A";
    const character2: string = "a";
    const character3: string = "5";
    const character4: string = "@";

    printCharacterBits(character1);
    console.log();

    printCharacterBits(character2);
    console.log();

    printCharacterBits(character3);
    console.log();

    printCharacterBits(character4);
    console.log();

    printBitsIndividually(character1);
} catch (error: unknown) {
    if (error instanceof Error) {
        console.error(`Error: ${error.message}`);
    } else {
        console.error("An unknown error occurred.");
    }
}



/*
run:

Character: 'A'
Decimal  : 65
Binary   : 01000001

Character: 'a'
Decimal  : 97
Binary   : 01100001

Character: '5'
Decimal  : 53
Binary   : 00110101

Character: '@'
Decimal  : 64
Binary   : 01000000

Bits for 'A': 0 1 0 0 0 0 0 1

*/

 



answered Oct 16 by avibootz
...