<?php
namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
class ConvertBinary extends ConvertBase
{
public static function toDecimal($value): string
{
try {
$value = self::validateValue(Functions::flattenSingleValue($value), true);
$value = self::validateBinary($value);
} catch (Exception $e) {
return $e->getMessage();
}
if (strlen($value) == 10) {
$value = substr($value, -9);
return '-' . (512 - bindec($value));
}
return bindec($value);
}
public static function toHex($value, $places = null): string
{
try {
$value = self::validateValue(Functions::flattenSingleValue($value), true);
$value = self::validateBinary($value);
$places = self::validatePlaces(Functions::flattenSingleValue($places));
} catch (Exception $e) {
return $e->getMessage();
}
if (strlen($value) == 10) {
return str_repeat('F', 8) . substr(strtoupper(dechex((int) bindec(substr($value, -9)))), -2);
}
$hexVal = (string) strtoupper(dechex((int) bindec($value)));
return self::nbrConversionFormat($hexVal, $places);
}
public static function toOctal($value, $places = null): string
{
try {
$value = self::validateValue(Functions::flattenSingleValue($value), true);
$value = self::validateBinary($value);
$places = self::validatePlaces(Functions::flattenSingleValue($places));
} catch (Exception $e) {
return $e->getMessage();
}
if (strlen($value) == 10) {
return str_repeat('7', 7) . substr(strtoupper(decoct((int) bindec(substr($value, -9)))), -3);
}
$octVal = (string) decoct((int) bindec($value));
return self::nbrConversionFormat($octVal, $places);
}
protected static function validateBinary(string $value): string
{
if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) {
throw new Exception(Functions::NAN());
}
return $value;
}
}