How to print the bits of a character in PHP

2 Answers

0 votes
$ch = 'a';

echo decbin(ord($ch));
 
 
/*
run:
      
1100001
     
*/

 



answered Mar 6, 2019 by avibootz
0 votes
declare(strict_types=1);

/**
 * Converts a single character to its 8-bit binary representation.
 *
 * @param string $char A single character.
 * @return string Binary representation of the character.
 *
 * @throws InvalidArgumentException If the input is not exactly one character.
 */
function charToBits(string $char): string
{
    if (strlen($char) !== 1) {
        throw new InvalidArgumentException(
            'Input must be exactly one character.'
        );
    }

    // Get the ASCII value of the character.
    $asciiCode = ord($char);

    // Convert to binary and pad with leading zeros.
    return str_pad(decbin($asciiCode), 8, '0', STR_PAD_LEFT);
}

/**
 * Prints a character and its binary representation.
 *
 * @param string $char A single character.
 */
function printCharacterBits(string $char): void
{
    $binary = charToBits($char);

    echo "Character: '{$char}'" . PHP_EOL;
    echo "Decimal  : " . ord($char) . PHP_EOL;
    echo 'Binary   : ' . $binary . PHP_EOL;
}

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

try {
    printCharacterBits('A');
    echo PHP_EOL;

    printCharacterBits('a');
    echo PHP_EOL;

    printCharacterBits('5');
    echo PHP_EOL;

    printCharacterBits('@');
} catch (InvalidArgumentException $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
}


/*
run:

Character: 'A'
Decimal  : 65
Binary   : 01000001

Character: 'a'
Decimal  : 97
Binary   : 01100001

Character: '5'
Decimal  : 53
Binary   : 00110101

Character: '@'
Decimal  : 64
Binary   : 01000000

*/

 



answered Oct 16 by avibootz
...