ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
ConvertHex.php
Go to the documentation of this file.
1 <?php
2 
4 
7 
8 class ConvertHex extends ConvertBase
9 {
35  public static function toBinary($value, $places = null): string
36  {
37  try {
38  $value = self::validateValue(Functions::flattenSingleValue($value));
39  $value = self::validateHex($value);
40  $places = self::validatePlaces(Functions::flattenSingleValue($places));
41  } catch (Exception $e) {
42  return $e->getMessage();
43  }
44 
45  $dec = self::toDecimal($value);
46 
47  return ConvertDecimal::toBinary($dec, $places);
48  }
49 
66  public static function toDecimal($value): string
67  {
68  try {
69  $value = self::validateValue(Functions::flattenSingleValue($value));
70  $value = self::validateHex($value);
71  } catch (Exception $e) {
72  return $e->getMessage();
73  }
74 
75  if (strlen($value) > 10) {
76  return Functions::NAN();
77  }
78 
79  $binX = '';
80  foreach (str_split($value) as $char) {
81  $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT);
82  }
83  if (strlen($binX) == 40 && $binX[0] == '1') {
84  for ($i = 0; $i < 40; ++$i) {
85  $binX[$i] = ($binX[$i] == '1' ? '0' : '1');
86  }
87 
88  return (string) ((bindec($binX) + 1) * -1);
89  }
90 
91  return (string) bindec($binX);
92  }
93 
123  public static function toOctal($value, $places = null): string
124  {
125  try {
126  $value = self::validateValue(Functions::flattenSingleValue($value));
127  $value = self::validateHex($value);
128  $places = self::validatePlaces(Functions::flattenSingleValue($places));
129  } catch (Exception $e) {
130  return $e->getMessage();
131  }
132 
133  $decimal = self::toDecimal($value);
134 
135  return ConvertDecimal::toOctal($decimal, $places);
136  }
137 
138  protected static function validateHex(string $value): string
139  {
140  if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) {
141  throw new Exception(Functions::NAN());
142  }
143 
144  return $value;
145  }
146 }
static toBinary($value, $places=null)
toBinary.
Definition: ConvertHex.php:35
static toOctal($value, $places=null)
toOctal.
Definition: ConvertHex.php:123
$i
Definition: disco.tpl.php:19
static flattenSingleValue($value='')
Convert an array to a single scalar value by extracting the first element.
Definition: Functions.php:649