Completed
Pull Request — master (#56)
by thomas
02:46
created

AbstractType::getMath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Buffertools\Types;
6
7
use BitWasp\Buffertools\ByteOrder;
8
9
abstract class AbstractType implements TypeInterface
10
{
11
    /**
12
     * @var
13
     */
14
    private $byteOrder;
15
16
    /**
17
     * @param int                  $byteOrder
18
     */
19 192
    public function __construct(int $byteOrder = ByteOrder::BE)
20
    {
21 192
        if (false === in_array($byteOrder, [ByteOrder::BE, ByteOrder::LE])) {
22 2
            throw new \InvalidArgumentException('Must pass valid flag for endianness');
23
        }
24
25 190
        $this->byteOrder = $byteOrder;
26 190
    }
27
28
    /**
29
     * @return int
30
     */
31 144
    public function getByteOrder(): int
32
    {
33 144
        return $this->byteOrder;
34
    }
35
36
    /**
37
     * @return bool
38
     */
39 132
    public function isBigEndian(): bool
40
    {
41 132
        return $this->getByteOrder() == ByteOrder::BE;
42
    }
43
44
    /**
45
     * @param string $bitString
46
     * @return string
47
     * @throws \Exception
48
     */
49 64
    public function flipBits(string $bitString): string
50
    {
51 64
        $length = strlen($bitString);
52
53 64
        if ($length % 8 !== 0) {
54 2
            throw new \Exception('Bit string length must be a multiple of 8');
55
        }
56
57 62
        $newString = '';
58 62
        for ($i = $length; $i >= 0; $i -= 8) {
59 62
            $newString .= substr($bitString, $i, 8);
60
        }
61
62 62
        return $newString;
63
    }
64
}
65