0

我正在使用 mpz_class(使用 MPIR 2.5.1 和 Visual Studio C++ 2010,以及 MPIR 的 C++ 版本),对我来说,在内存中存储大量数字是不可行的,所以我想用二进制文件来做。

我已经用文本文件完成了这个,但是当我使用 100,000+ 位数时,二进制文件应该(希望)节省大量空间。

我写了一个简短的例子来帮助你理解我想要做什么:

ofstream binFile;
binFile.open ("binary.bin", ios::out | ios::binary);

mpz_class test;
test.set_str("999999999999999",10);

binFile.write((char *)(&test), sizeof(test));

cout << "NUMBER: " << test << "\tSIZE: " << sizeof(test) << endl;
binFile.close();

我正在尝试编写表示 mpz_class 实例的字符数据。然后,为了测试它,我尝试读取文件:

ifstream binFile2;
binFile2.open("binary.bin", ios::in | ios::binary);

mpz_class num1 = 0; 
binFile2.read ((char *)(&num1), sizeof(num1));

cout << "NUMBER: " << num1 << "\tSIZE: " << sizeof(num1) << endl;
binFile2.close();

我在网上看到的许多示例都使用这种方法将类数据存储到二进制文件中,但我的输出是这样的:

NUMBER: 999999999999999 SIZE: 12

NUMBER: 8589934595      SIZE: 12

为什么不能直接存储类数据,然后再读取呢?mpz_class 的实例不可能是 12 的大小,这是指针的大小吗?

我也试过这个,但我认为它基本上是一样的:

char* membuffer = new char[12]; //sizeof(test) returned 12
binFile2.read (membuffer , sizeof(test));
memcpy(&test, &membuffer, sizeof(test))

任何有关如何解决此问题的建议将不胜感激。谢谢。

4

1 回答 1

1

I think you need to spend more time with the GMP manual (section 12.1):

Conversions back from the classes to standard C++ types aren’t done automatically, instead member functions like get_si are provided (see the following sections for details).

So, what you probably need to do is call mpz_class::get_str and mpz_class::set_str. Anyway, the C++ interface is just a light wrapper around the C API, so you're probably better off using the low-level stuff, since it's much better documented. In this case, you would have to use mpz_get_str and mpz_set_str (for integers).

Just keep in mind that there's no API function that can provide a direct binary serialization of the GMP data types, so you need to work with strings. I'm not sure if there are certain limitations to the size of these beasts, so you should test your code thoroughly if you plan to make use of such large numbers. Maybe the best choice is to extract a string representation in base 62 (maximum allowed) so that it doesn't blow up your memory (in base 2 it will eat up one byte for every bit) and then write that to file.

于 2012-09-11T13:58:28.733 回答