diff --git a/include/BigInt.hpp b/include/BigInt.hpp index e3be86c..496c2b9 100644 --- a/include/BigInt.hpp +++ b/include/BigInt.hpp @@ -90,6 +90,11 @@ class BigInt { bool operator==(const std::string&) const; bool operator!=(const std::string&) const; + // Bitwise operators: + BigInt operator<<(const int&) const; + BigInt operator>>(const int&) const; + + // I/O stream operators: friend std::istream& operator>>(std::istream&, BigInt&); friend std::ostream& operator<<(std::ostream&, const BigInt&); diff --git a/include/operators/bitwise.hpp b/include/operators/bitwise.hpp new file mode 100644 index 0000000..be0962a --- /dev/null +++ b/include/operators/bitwise.hpp @@ -0,0 +1,71 @@ +/* + =========================================================================== + Bitwise operators + =========================================================================== +*/ + +#ifndef BIG_INT_BITWISE_OPERATORS_HPP +#define BIG_INT_BITWISE_OPERATORS_HPP + +#include +#include +#include + +#include "BigInt.hpp" + +/* + BigInt << int + --------------- + Shifts the BigInt left by `num` bits. + NOTE: Negative `nums` are accepted and converted inside the function. +*/ + +BigInt BigInt::operator<<(const int& num) const { + BigInt result = *this; + char originalSign = this->sign; // store sign separately because consecutive multiplications will lose track of the original sign + + // throw error if num < 0 + if (num < 0) { + throw std::invalid_argument("Expected non-negative integer"); + } + + for (int i = 0; i < num; i++) { + result *= 2; + } + + result.sign = originalSign; + + return result; +} + +/* + BigInt >> int + --------------- + Shifts the BigInt right by `num` bits. + NOTE: Negative `nums` are accepted and converted inside the function. +*/ + +BigInt BigInt::operator>>(const int& num) const { + BigInt result = *this; + char originalSign = this->sign; // store sign separately because consecutive divisions will lose track of the original sign + + // throw error if num < 0 + if (num < 0) { + throw std::invalid_argument("Expected non-negative integer"); + } + + for (int i = 0; i < num; i++) { + result /= 2; + + if(result == 0) { // if all bits are 0 + result = BigInt(); + return result; + } + } + + result.sign = originalSign; + + return result; +} + +#endif // BIG_INT_BITWISE_OPERATORS_HPP \ No newline at end of file diff --git a/scripts/release.sh b/scripts/release.sh index bc866bb..915f8a9 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -38,7 +38,8 @@ header_files="BigInt.hpp \ operators/binary_arithmetic.hpp \ operators/arithmetic_assignment.hpp \ operators/increment_decrement.hpp \ - operators/io_stream.hpp" + operators/io_stream.hpp \ + operators/bitwise.hpp" # append the contents of each header file to the release file for file in $header_files