= ($base / 2))) ? ($base - 1) : 0); // get the extension digit return str_pad((string)($num), $exnd, $extd, STR_PAD_LEFT); // extend to the left } public static function complement(string $num, int $base): string { // convert to an integer $M = (int)(base_convert($num, $base, 10)); // check if the highest digit is less than the half of the base, if not, add a zero prefix $fd = (int)(base_convert($num[0], $base, 10)); // create the basis for forming the complement $H = (string)($base - 1); $K_str = (int)(str_repeat($H, strlen($num))); if ($fd >= ($base / 2)) { // if one more digit is needed... $K_str = $H . $K_str; // prepend with a zero digit } // convert to integer $K = (int)(base_convert($K_str, $base, 10)); // form the base's complement $C = $K - $M + 1; // convert to the final base return base_convert((string)$C, 10, $base); } public static function changeRepresentation(int $num, int $base, string $rep, int $digits): string { $neg = $num < 0; // store if the value is negative $numa_str = (string)(abs($num)); // create the absolute value as a string $numa_str = base_convert($numa_str, 10, $base); // convert to specific base if ($neg) { if ($rep === "s") { $numa_str = self::extend($numa_str, $base, $digits, false); $numa_str = "-" . $numa_str; } else if ($rep === "c") { $numa_str = self::complement($numa_str, $base); $numa_str = self::extend($numa_str, $base, $digits, true); } } else { $numa_str = self::extend($numa_str, $base, $digits, false); if (($rep === "c") && ($numa_str[0] >= ($base / 2))) { $numa_str = "0" . $numa_str; } } return $numa_str; } }