如何以字节为单位计算mpz_class的长度?
How to calculate the length of a mpz_class in bytes?
我想用填充实现RSA,但首先我必须找出消息的长度(以字节为单位(,这是一个mpz_class项。cpp 中的哪个函数对完成此操作有用?
const mpz_class m(argv[1])
m 的长度是多少(以字节为单位(? 谢谢!
@Shawn的评论是正确的:你的类在内存中占用的字节不是你应该关心的。字节在内存中的位置不仅取决于编译器决定如何打包它们,而且它们的顺序还取决于所使用的硬件。
因此,与其做一些笨拙且非常脆弱的memcopy之类的事情,几乎肯定会在某个时候中断,不如自己构建消息(google关键字:序列化(。这也有一个优点,即您的类可以包含您不想添加到消息中的内容(带有临时结果的缓存或其他实现/优化内容(。
据我所知C++(与 f.ex 不同。C#( 不附带内置序列化支持,但可能存在可以为您完成大量序列化的库。否则,您只需自己编写"数据成员到字节数组"函数即可。
超级简单的例子:
#include <vector>
#include<iostream>
class myClass
{
int32_t a;
public:
myClass(int32_t val) : a(val) {}
// Deserializer
bool initFromBytes(std::vector<uint8_t> msg)
{
if (msg.size() < 4)
return false;
a = 0;
for (int i = 0; i < 4; ++i)
{
a += msg[i] << (i * 8);
}
return true;
}
// Serializer
std::vector<uint8_t> toBytes()
{
std::vector<uint8_t> res;
for (int i = 0; i < 4; ++i)
{
res.push_back(a >> (i*8));
}
return res;
}
void print() { std::cout << "myClass: " << a << std::endl; }
};
int main()
{
myClass myC(123456789);
myC.print();
std::vector<uint8_t> message = myC.toBytes();
myClass recreate(0);
if (recreate.initFromBytes(message))
recreate.print();
else
std::cout << "Error" << std::endl;
return 0;
}
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- "Undefined class"作为is_base_of的论据
- 如何将class.cpp和class.hpp编译为一个.o文件
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何使用"derived input class"创建派生类?
- 错误:"Left of getValue must have class/struct/union"
- ' class a : b ' 和 ' class a : public b ' 之间的继承类不同
- Pybind11 Class Definition
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- C2011 'CMemDC':Visual Studio 2019中的'class'类型重新定义
- TypeError: [c++ addon class] 不是构造函数
- C++ class template
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- Clearing Class Foo with new(pFoo) Foo()
- C++ class vs a library
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 使用"class"关键字,后跟未声明的标识符
- VSCode - C++对"CLASS::FUNCTION"的未定义引用