zmodn

A simple C++ library for integers modulo N
git clone https://git.tronto.net/zmodn
Download | Log | Files | Refs | README

bitint_wrapper.h (1782B)


      1 #ifndef BITINT_WRAPPER_H
      2 #define BITINT_WRAPPER_H
      3 
      4 #include <cstdio>
      5 #include <iostream>
      6 
      7 // Wrapper class for _BitInt(N) (port of the C23 feature, compiler
      8 // extension for C++ available in Clang and maybe GCC). This is needed
      9 // because operator<< is not defined on _BitInt(N), apparently.
     10 
     11 template<uint64_t N = 128>
     12 class BitInt {
     13 public:
     14 	_BitInt(N) x;
     15 
     16 	constexpr BitInt() : x{_BitInt(N)(0)} {}
     17 	constexpr BitInt(int n) : x{_BitInt(N)(n)} {}
     18 	constexpr BitInt(long long n) : x{_BitInt(N)(n)} {}
     19 	constexpr BitInt(_BitInt(N) n) : x{n} {}
     20 	constexpr auto operator<=>(const BitInt& b) const { return x <=> b.x; }
     21 	constexpr bool operator==(const BitInt& b) const = default;
     22 	constexpr BitInt operator+(const BitInt& b) const { return x + b.x; }
     23 	constexpr BitInt operator-(const BitInt& b) const { return x - b.x; }
     24 	constexpr BitInt operator*(const BitInt& b) const { return x * b.x; }
     25 	constexpr BitInt operator/(const BitInt& b) const { return x / b.x; }
     26 	constexpr BitInt operator%(const BitInt& b) const { return x % b.x; }
     27 	constexpr BitInt operator-() const { return -x; }
     28 	constexpr BitInt operator+=(const BitInt& b) { return *this = *this + b; }
     29 	constexpr BitInt operator-=(const BitInt& b) { return *this = *this - b; }
     30 	constexpr BitInt operator*=(const BitInt& b) { return *this = *this * b; }
     31 	constexpr BitInt operator/=(const BitInt& b) { return *this = *this / b; }
     32 	constexpr BitInt operator%=(const BitInt& b) { return *this = *this % b; }
     33 
     34 	friend std::ostream& operator<<(std::ostream& os, const BitInt<N>& b) {
     35 		if (b > 0) {
     36 			std::string s;
     37 			auto bb = b;
     38 			while (bb != 0) {
     39 				char c = (bb.x % 10) + '0';
     40 				s = c + s;
     41 				bb /= 10;
     42 			}
     43 			return os << s;
     44 		} else if (b < 0) {
     45 			return os << "-" << -b;
     46 		} else return os << "0";
     47 	}
     48 };
     49 
     50 #endif