Completed
Pull Request — master (#317)
by thomas
16:45 queued 06:42
created

BinaryMath::makeNegative()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace BitWasp\Bitcoin\Math;
4
5
use Mdanter\Ecc\Math\GmpMathInterface;
6
7
class BinaryMath
8
{
9
    /**
10
     * @var GmpMathInterface
11
     */
12
    private $math;
13
14
    /**
15
     * @param GmpMathInterface $math
16
     */
17 21
    public function __construct(GmpMathInterface $math)
18
    {
19 21
        $this->math = $math;
20 21
    }
21
22
    /**
23
     * @param int $bitSize
24
     * @return int
25
     */
26 21
    private function fixSize($bitSize)
27
    {
28 21
        return $bitSize - 1;
29
    }
30
31
    /**
32
     * @param \GMP $integer
33
     * @param int $bitSize
34
     * @return bool
35
     */
36 21
    public function isNegative(\GMP $integer, $bitSize)
37
    {
38 21
        return $this->math->cmp($this->math->rightShift($integer, $this->fixSize($bitSize)), gmp_init(1)) === 0;
39
    }
40
41
    /**
42
     * @param \GMP $integer
43
     * @param int $bitSize
44
     * @return \GMP
45
     */
46
    public function makeNegative(\GMP $integer, $bitSize)
47
    {
48
        return $this->math->bitwiseXor($this->math->leftShift(gmp_init(1), $this->fixSize($bitSize)), $integer);
49
    }
50
51
    /**
52
     * @param \GMP $integer
53
     * @param int $bitSize
54
     * @return \GMP
55
     */
56
    public function getTwosComplement(\GMP $integer, $bitSize)
57
    {
58
        return $this->math->add($this->math->pow(gmp_init(2), $bitSize), $integer);
59
    }
60
}
61