-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathdecode.php
36 lines (30 loc) · 947 Bytes
/
decode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
declare(strict_types=1);
namespace Psl\Encoding\Hex;
use Psl\Encoding\Exception;
use Psl\Str;
/**
* Convert a hexadecimal string into a binary string.
*
* Hex ( Base16 ) character set:
* [0-9] [a-f] [A-F]
* 0x30-0x39, 0x61-0x66, 0x41-0x46
*
* @pure
*
* @throws Exception\RangeException If the hexadecimal string contains characters outside the base16 range,
* or an odd number of characters.
*/
function decode(string $hexadecimal): string
{
if (!ctype_xdigit($hexadecimal)) {
throw new Exception\RangeException(
'The given hexadecimal string contains characters outside the base16 range.',
);
}
$hex_len = Str\length($hexadecimal, Str\Encoding::Ascii8bit);
if (($hex_len & 1) !== 0) {
throw new Exception\RangeException('Expected an even number of hexadecimal characters.');
}
return (string) hex2bin($hexadecimal);
}