Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions include/BigInt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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&);
Expand Down
71 changes: 71 additions & 0 deletions include/operators/bitwise.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
===========================================================================
Bitwise operators
===========================================================================
*/

#ifndef BIG_INT_BITWISE_OPERATORS_HPP
#define BIG_INT_BITWISE_OPERATORS_HPP

#include <iostream>
#include <stdexcept>
#include <string>

#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
3 changes: 2 additions & 1 deletion scripts/release.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down