How to print the bits of a character in JavaScript

2 Answers

0 votes
function get_bits(ch){
    return (ch.charCodeAt(0) >>> 0).toString(2);
}
 
const ch = 'a';
  
console.log(get_bits(ch));
 
 
/*
run:
    
1100001
     
*/

 



answered Mar 6, 2019 by avibootz
edited Oct 15 by avibootz
0 votes
"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

     
*/

 



answered Oct 15 by avibootz
...