diff --git a/lib/BigInteger.php b/lib/BigInteger.php index 2ac6dad..3c710df 100644 --- a/lib/BigInteger.php +++ b/lib/BigInteger.php @@ -625,6 +625,20 @@ 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)); + } + + 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; + } } } 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");