ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
ConvertBinary.php
Go to the documentation of this file.
1 <?php
2 
4 
7 
9 {
25  public static function toDecimal($value): string
26  {
27  try {
28  $value = self::validateValue(Functions::flattenSingleValue($value));
29  $value = self::validateBinary($value);
30  } catch (Exception $e) {
31  return $e->getMessage();
32  }
33 
34  if (strlen($value) == 10) {
35  // Two's Complement
36  $value = substr($value, -9);
37 
38  return '-' . (512 - bindec($value));
39  }
40 
41  return (string) bindec($value);
42  }
43 
65  public static function toHex($value, $places = null): string
66  {
67  try {
68  $value = self::validateValue(Functions::flattenSingleValue($value));
69  $value = self::validateBinary($value);
70  $places = self::validatePlaces(Functions::flattenSingleValue($places));
71  } catch (Exception $e) {
72  return $e->getMessage();
73  }
74 
75  if (strlen($value) == 10) {
76  $high2 = substr($value, 0, 2);
77  $low8 = substr($value, 2);
78  $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF'];
79 
80  return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2));
81  }
82  $hexVal = (string) strtoupper(dechex((int) bindec($value)));
83 
84  return self::nbrConversionFormat($hexVal, $places);
85  }
86 
108  public static function toOctal($value, $places = null): string
109  {
110  try {
111  $value = self::validateValue(Functions::flattenSingleValue($value));
112  $value = self::validateBinary($value);
113  $places = self::validatePlaces(Functions::flattenSingleValue($places));
114  } catch (Exception $e) {
115  return $e->getMessage();
116  }
117 
118  if (strlen($value) == 10 && substr($value, 0, 1) === '1') { // Two's Complement
119  return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value")));
120  }
121  $octVal = (string) decoct((int) bindec($value));
122 
123  return self::nbrConversionFormat($octVal, $places);
124  }
125 
126  protected static function validateBinary(string $value): string
127  {
128  if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) {
129  throw new Exception(Functions::NAN());
130  }
131 
132  return $value;
133  }
134 }
static flattenSingleValue($value='')
Convert an array to a single scalar value by extracting the first element.
Definition: Functions.php:649