c++使用int128
C++中没有直接支持int128的数据类型,但可以通过以下方法模拟实现:
- 使用结构体或类:
struct Int128 {
long long high;
unsigned long long low;
};
Int128 operator+(const Int128& a, const Int128& b) {
Int128 result;
result.low = a.low + b.low;
result.high = a.high + b.high + (result.low < a.low);
return result;
}
Int128 operator-(const Int128& a, const Int128& b) {
Int128 result;
result.low = a.low - b.low;
result.high = a.high - b.high - (result.low > a.low);
return result;
}
// 其他运算符和函数的实现类似,略...
- 使用第三方库: 可以使用一些第三方库,如Boost库,它提供了int128_t数据类型和相关的运算符重载。
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
int main() {
int128_t a = 123456789;
int128_t b = 987654321;
int128_t c = a + b;
std::cout << c << std::endl;
return 0;
}
需要注意的是,使用int128可能会导致代码的可移植性问题,因为不是所有的编译器都支持int128。
原文地址: http://www.cveoy.top/t/topic/i8Eq 著作权归作者所有。请勿转载和采集!