Operácie s binárnymi číslami PHP
<?php class Binary { public function prepareNumber($num, $length) { for ($i = $length - 1; $i >= 0; $i--) { $result[$i] = 0; } for ($i = strlen($num) - 1; $i >= 0; $i--) { $result[$i] = $num[$i]; } return implode('', $result); } public function sum($num1, $num2, $length = 8) { for ($i = $length - 1; $i >= 0; $i--) { $result[$i] = 0; } for ($i = $length - 1; $i >= 0; $i--) { $result[$i] = $num1[$i] + $num2[$i] + $result[$i]; if ($result[$i] > 1) { $result[$i] = $result[$i] == 2 ? 0 : 1; $result[$i-1] = 1; } } return $result; } public function sub($num1, $num2, $length = 8) { return $this->sum($num1, $this->negate($num2)); } public function negate($num) { $length = strlen($num) - 1; for ($i = $length; $i >= 0; $i--) $num[$i] = $num[$i] == 1 ? 0 : 1; return implode('', $this->sum($num, $this->prepareNumber('1', $length + 1))); } public function check($num1, $num2) { $num1 = intval($num1); $num2 = intval($num2); if ($num1 > $num2) return -1; else if ($num1 < $num) return 1; else return 0; } } $bin = new Binary(); $input_1 = $bin->prepareNumber('11', 8); $input_2 = $bin->prepareNumber('1', 8); $number = $bin->sum($input_1, $input_2); for ($i = 0; $i < sizeof($number); $i++) { echo($number[$i]); } echo('<p>'); $number = $bin->sub($input_1, $input_2); for ($i = 0; $i < sizeof($number); $i++) { echo($number[$i]); } echo('<p>'); echo($bin->check($input_1, $input_2)); ?>