<?php
function hitungNomorBit(int $angka, int $nomorBit): ?int {
    if ($angka < 0 || $nomorBit < 0) return null;

    // Konversi manual desimal ke biner dari MSB ke LSB
    $biner = [];
    while ($angka > 0) {
        array_unshift($biner, $angka % 2);
        $angka = intdiv($angka, 2);
    }

    if ($nomorBit >= count($biner)) return null;

    $jumlah = 0;
    for ($i = 0; $i <= $nomorBit; $i++) {
        if ($biner[$i] === 1) {
            $jumlah++;
        }
    }

    return $jumlah;
}

echo hitungNomorBit(13, 0) . "\n"; // Output: 1 (bit 0 = 1)
echo hitungNomorBit(13, 1) . "\n"; // Output: 3 (bit 1 ke bawah: 1+0+1)
var_dump(hitungNomorBit(13, 2));   // Output: null (bit 2 = 0, hanya sampai 2, jadi total 2 bit yang 1)