fork download
  1. <?php
  2. function hitungNomorBit($angka, $nomorBit) {
  3. // Konversi manual ke biner (array dari kanan ke kiri)
  4. $biner = [];
  5. $n = $angka;
  6. if ($n == 0) $biner[] = 0;
  7. while ($n > 0) {
  8. $biner[] = $n % 2;
  9. $n = intdiv($n, 2);
  10. }
  11. // Kembalikan nilai bit ke-n jika ada, null jika tidak ada
  12. if ($nomorBit >= 0 && $nomorBit < count($biner)) {
  13. return $biner[$nomorBit];
  14. }
  15. return null;
  16. }
  17.  
  18. function cetakBitDanDesimal($angka, $nomorBit) {
  19. $bit = hitungNomorBit($angka, $nomorBit);
  20. if ($bit === null) {
  21. echo "Bit ke-$nomorBit: NULL = NULL\n";
  22. } elseif ($bit == 1) {
  23. echo "Bit ke-$nomorBit: 1 = " . (2 ** $nomorBit) . "\n";
  24. } else {
  25. echo "Bit ke-$nomorBit: 0 = NULL \n";
  26. }
  27. }
  28.  
  29. // test
  30. cetakBitDanDesimal(13, 0); // Bit ke-0: 1 = 1
  31. cetakBitDanDesimal(13, 1); // Bit ke-1: 0 =
  32. cetakBitDanDesimal(13, 2); // Bit ke-2: 1 = 4
  33. cetakBitDanDesimal(19, 4); // Bit ke-4: 1 = 16
  34. cetakBitDanDesimal(9, 0); // Bit ke-0: 1 = 1
  35. cetakBitDanDesimal(9, 1); // Bit ke-0: 1 = 1
  36. cetakBitDanDesimal(9, 3); // Bit ke-3: 1 = 8
  37. ?>
Success #stdin #stdout 0.03s 25364KB
stdin
Standard input is empty
stdout
Bit ke-0: 1 = 1
Bit ke-1: 0 = NULL 
Bit ke-2: 1 = 4
Bit ke-4: 1 = 16
Bit ke-0: 1 = 1
Bit ke-1: 0 = NULL 
Bit ke-3: 1 = 8