gcc 本身具有 __int128 类型。
但是limits.h中没有定义。我的意思是没有像
INT128_MAX
或INT128_MIN
这样的东西......
gcc 将文字常量解释为 64 位整数。这意味着如果我写
#define INT128_MIN −170141183460469231731687303715884105728
它会抱怨类型告诉它已经截断了值。
这对于在阵列上移动尤其烦人。如何克服这个?
static const __uint128_t UINT128_MAX =__uint128_t(__int128_t(-1L));
static const __int128_t INT128_MAX = UINT128_MAX >> 1;
static const __int128_t INT128_MIN = -INT128_MAX - 1;
别开玩笑了,把它用于无符号最大值:
static const __uint128_t UINT128_MAX = ~__uint128_t{};
编辑:您可能想看看这些:
template <typename U>
constexpr static auto bit_size_v(CHAR_BIT * sizeof(U));
template <typename U>
constexpr static U min_v(std::is_signed_v<U> ? U(1) << (bit_size_v<U> - 1) : U{});
template <typename U>
constexpr static U max_v(~(std::is_signed_v<U> ? min_v<U> : U{}));
因为你有标签 [g++],我假设你对 C++ 解决方案感兴趣:通常的
std::numeric_limits<__int128>::max()
就可以了......
由于目前gcc不支持定义int128整数文字,通常使用
(high<<64)|low
.组合int128
但是这个来源有一个完美的答案:
#define INT128_MAX (__int128)(((unsigned __int128) 1 << ((sizeof(__int128) * __CHAR_BIT__) - 1)) - 1)
#define INT128_MIN (-INT128_MAX - 1)
#define UINT128_MAX ((2 * (unsigned __int128) INT128_MAX) + 1)
INT128_MAX
是 2^127 - 1
是 (1 << 127) - 1
。然后可以计算其余常数。
在性能和内存使用方面并不理想,但这是我唯一发现的。当然,这在未授权未对齐内存访问的体系结构上根本不起作用。
const __int128 llong_min=*(__int128*)"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfd";
const __int128 llong_max=*(__int128*)"\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";