From 6ea50941e5e31241eee573f9fdde7366f75955d3 Mon Sep 17 00:00:00 2001 From: Ruslan Gataullin Date: Tue, 24 Mar 2020 13:55:52 +0500 Subject: [PATCH 1/3] Added shiftLeft method based on https://docs.microsoft.com/ru-ru/dotnet/api/system.numerics.biginteger.op_leftshift --- lib/BigInteger.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/BigInteger.php b/lib/BigInteger.php index 2ac6dad..b393bdc 100644 --- a/lib/BigInteger.php +++ b/lib/BigInteger.php @@ -625,6 +625,10 @@ public function equals($x) { public function sign() { return $this->value[0] === "-" ? -1 : ($this->value === "0" ? 0 : 1); } + + public function shiftLeft($n) { + return $this->mul((new static(2))->pow($n)); + } } } From c137edae9a8f2bbd66cd02e85da0fc4adca846bd Mon Sep 17 00:00:00 2001 From: Ruslan Gataullin Date: Tue, 24 Mar 2020 13:56:17 +0500 Subject: [PATCH 2/3] Added shiftRight method https://docs.microsoft.com/ru-ru/dotnet/api/system.numerics.biginteger.op_rightshift --- lib/BigInteger.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/BigInteger.php b/lib/BigInteger.php index b393bdc..3c710df 100644 --- a/lib/BigInteger.php +++ b/lib/BigInteger.php @@ -629,6 +629,16 @@ public function sign() { public function shiftLeft($n) { return $this->mul((new static(2))->pow($n)); } + + public function shiftRight($n) { + $newInt = $this->div((new static(2))->pow($n)); + + if ($newInt->add($n)->cmp(0) < 0) { + return $newInt->sub(1); + } + + return $newInt; + } } } From 473a41bab030b5d33d2042bfc234813510431fa2 Mon Sep 17 00:00:00 2001 From: Ruslan Gataullin Date: Tue, 24 Mar 2020 13:56:33 +0500 Subject: [PATCH 3/3] Added tests for both new methods --- test/test.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/test.php b/test/test.php index 2fc71bf..4fbe543 100644 --- a/test/test.php +++ b/test/test.php @@ -74,6 +74,8 @@ function testOp() { testB((new BigInteger(20))->binaryAnd(18), "16", "binaryAnd"); testB((new BigInteger(20))->binaryOr(18), "22", "binaryOr"); testB((new BigInteger(20))->binaryXor(18), "6", "binaryXor"); + testB((new BigInteger(3))->shiftLeft(4), "48", "shiftLeft"); + testB((new BigInteger(3))->shiftRight(4), "0", "shiftRight"); testB((new BigInteger(20))->setbit(3), "28", "setbit"); test((new BigInteger(20))->testbit(4), true, "testbit true"); test((new BigInteger(20))->testbit(3), false, "testbit false");