C/C++中int128的那点事
TRUE3494063625 · · 个人记录
C/C++中int128的那点事
最近群友(人家的)对int128这个东西讨论的热火朝天的。讲道理的话,编译器的gcc是不支持__int128这种数据类型的,比如在__int128这种数据类型的,因此要自己实现IO,其他的运算,与int没有什么不同。
但是官方上写了__int128_t和__uint128_t,分别用于声明有符号整数变量和无符号整数变量。
有关GCC的文档参见:Using the GNU Compiler Collection (GCC)。
这里给出了样例程序,是有关类型__int128_t和__uint128_t的。从计算可以看出,这两个类型都是__uint128_t是
由于这种大整数无法使用函数printf()输出其值,所以自己(人家)做了一个整数转字符串函数myitoa(),用于实现128位整数的输出。
有兴趣的同学(没兴趣)想了解底层实现原理可以参看我(人家的)的Github上:https://github.com/AngelKitty/English-Version-CHSInt128
代码实现如下:
1 #include <iostream>
2
3 using namespace std;
4
5 void myitoa(__int128_t v, char* s)
6 {
7 char temp;
8 int i=0, j;
9
10 while(v >0) {
11 s[i++] = v % 10 + '0';
12 v /= 10;
13 }
14 s[i] = '\0';
15
16 j=0;
17 i--;
18 while(j < i) {
19 temp = s[j];
20 s[j] = s[i];
21 s[i] = temp;
22 j++;
23 i--;
24 }
25 }
26
27 int main()
28 {
29 __uint128_t n = 0;
30
31 n = ~n;
32 int count = 0;
33 while(n > 0) {
34 count++;
35 n >>= 1;
36 }
37
38 cout << "count=" << count << endl;
39 cout << "__uint128_t size=" << sizeof(__uint128_t) << endl;
40 cout << endl;
41
42 cout << "__int128_t size=" << sizeof(__int128_t) << endl;
43
44 __int128_t x = 1100000000000000L;
45 __int128_t y = 2200000000000000L;
46 char s[40];
47
48 x *= y;
49
50 myitoa(x, s);
51
52 cout << "x=" << s << endl;
53
54 return 0;
55 }
打印结果如下:
count=128
__uint128_t size=16
__int128_t size=16
x=2420000000000000000000000000000
以下是__int128的
a+b大数读入模板:
#include <bits/stdc++.h>
using namespace std;
inline __int128 read(){
__int128 x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
inline void print(__int128 x){
if(x<0){
putchar('-');
x=-x;
}
if(x>9)
print(x/10);
putchar(x%10+'0');
}
int main(void){
__int128 a = read();
__int128 b = read();
print(a + b);
return 0;
}
测试了一下,
另外关于不是我)提供了一个好的实现机制,源码我已经上传,下载链接在这里:
运行结果可以看到如下所示:
Project Samples
作 者(不是我):
出 处: