1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?php
$nbr = 192; // à modifier
$decimal_tab = array(128,64,32,16,8,4,2,1);
$tab = [];
$total = 0;
if ($nbr <= 255 && $nbr >=0) {
for ($i = 0 ; $i < count($decimal_tab) ; $i++){
$total += $decimal_tab[$i];
if ($total < $nbr) {
$tab[] = $decimal_tab[$i];
}
elseif ($total > $nbr) {
$total -= $decimal_tab[$i];
$tab[] = 0;
continue;
}
else {
$tab[] = $decimal_tab[$i];
}
}
// conversion binaire
echo "Conversion en binaire : $nbr = ";
for ($i = 0; $i < count($tab) ; $i++){
if ($tab[$i] != 0 ) {
echo 1;
}
else {
echo 0;
}
}
} else {
echo "Le chiffre doit être compris entre 0 et 255";
} |
Partager