我目前正在尝试实现一个可以计算一些加密哈希函数的程序。我正在制作一个 BigInt 类,我希望它能让我用任意大小的整数进行基本的数学和逻辑运算。
我正在学习的部分课程:
class BigInt
{
std::vector<unsigned int> num;
BigInt operator+ (BigInt num_to_add)
{
//Implementation
}
}
我希望有一些方法可以添加无符号整数并获得溢出位,以及将这个溢出位传递给下一个整数的方法,就像在汇编语言中一样,我相信 ARM 汇编中的操作码是'ADCS' 将设置溢出位,并将溢出位带入下一个加法和。但是,我四处搜索,似乎在 C++ 语言中找不到任何功能。
编辑:以防万一有人偶然发现,这是我对加法功能的实现。
class big_int
{
public:
std::vector<unsigned int> num;
big_int(std::vector<unsigned int> num)
{
this->num = num;
}
big_int operator+ (unsigned int num_to_add)
{
bool carry_flag = true;
std::vector<unsigned int> output_num;
for (unsigned int num_part : num)
{
unsigned int value = num_part;
if(carry_flag)
{
value = num_part + num_to_add;
}
else
{
value = num_part;
}
carry_flag = false;
if (value < num_to_add || value < num_part)
{
carry_flag = true;
num_to_add = 1;
output_num.push_back(value);
}
else
{
output_num.push_back(value);
}
}
if (carry_flag)
{
output_num.push_back(1);
}
big_int out_obj(output_num);
return out_obj;
}
big_int operator+ (big_int num_to_add)
{
int smallest_size;
int largest_size;
std::vector<unsigned int> largest_num;
if (num.size() > num_to_add.num.size())
{
largest_size = num.size();
smallest_size = num_to_add.num.size();
largest_num = num;
}
else
{
largest_size = num_to_add.num.size();
smallest_size = num.size();
largest_num = num_to_add.num;
}
bool carry_flag = false;
std::vector<unsigned int> out_num;
for(int i = 0; i < smallest_size; i++)
{
unsigned int num_a = num[i];
unsigned int num_b = num_to_add.num[i];
unsigned int result;
if (carry_flag)
{
result = num_a + num_b + 1;
}
else
{
result = num_a + num_b;
}
carry_flag = false;
if (result < num_a || result < num_b)
{
carry_flag = true;
}
out_num.push_back(result);
}
std::vector<unsigned int> rest_of_largest_num;
if (smallest_size == largest_size)
{
if (carry_flag)
{
out_num.push_back(1);
}
}
else
{
for(int i = smallest_size; i < largest_size; i++)
{
rest_of_largest_num.push_back(largest_num[i]);
}
if (carry_flag)
{
big_int rest_of_largest_num_obj(rest_of_largest_num);
rest_of_largest_num_obj = rest_of_largest_num_obj + 1;
rest_of_largest_num = rest_of_largest_num_obj.num;
}
}
for (int i = 0; i < rest_of_largest_num.size(); i++)
{
out_num.push_back(rest_of_largest_num[i]);
}
big_int out_obj(out_num);
return out_obj;
}
};