[英]Converting many bits to Base 10
我正在C ++中建立一个类,该类可用于存储任意大整数。 我将它们作为二进制存储在向量中。 我需要能够以10为底打印此向量,以便人类更容易理解。 我知道我可以将其转换为int然后输出该int。 但是,我的数字将比任何原始类型大得多。 如何将其直接转换为字符串。
到目前为止,这是我的代码。 我是C ++的新手,所以如果您有其他建议也可以。 我需要填写string toBaseTenString()
函数的帮助。
class BinaryInt
{
private:
bool lastDataUser = true;
vector<bool> * data;
BinaryInt(vector<bool> * pointer)
{
data = pointer;
}
public:
BinaryInt(int n)
{
data = new vector<bool>();
while(n > 0)
{
data->push_back(n % 2);
n = n >> 1;
}
}
BinaryInt(const BinaryInt & from)
{
from.lastDataUser = false;
this->data = from.data;
}
~BinaryInt()
{
if(lastDataUser)
delete data;
}
string toBinaryString();
string toBaseTenString();
static BinaryInt add(BinaryInt a, BinaryInt b);
static BinaryInt mult(BinaryInt a, BinaryInt b);
};
BinaryInt BinaryInt::add(BinaryInt a, BinaryInt b)
{
int aSize = a.data->size();
int bSize = b.data->size();
int newDataSize = max(aSize, bSize);
vector<bool> * newData = new vector<bool>(newDataSize);
bool carry = 0;
for(int i = 0; i < newDataSize; i++)
{
int sum = (i < aSize ? a.data->at(i) : 0) + (i < bSize ? b.data->at(i) : 0) + carry;
(*newData)[i] = sum % 2;
carry = sum >> 1;
}
if(carry)
newData->push_back(carry);
return BinaryInt(newData);
}
string BinaryInt::toBinaryString()
{
stringstream ss;
for(int i = data->size() - 1; i >= 0; i--)
{
ss << (*data)[i];
}
return ss.str();
}
string BinaryInt::toBaseTenString()
{
//Not sure how to do this
}
我知道您在OP中说过:“我的数字将比任何原始类型大得多”,但请听我说一下。
过去,我使用std :: bitset处理数字的二进制表示形式,并从其他各种表示形式来回转换。 std :: bitset本质上是一个花哨的std :: vector,带有一些附加功能。 如果听起来很有趣,您可以在此处阅读更多信息,但是这里有一些愚蠢的示例代码,向您展示了它是如何工作的:
std::bitset<8> myByte;
myByte |= 1; // mByte = 00000001
myByte <<= 4; // mByte = 00010000
myByte |= 1; // mByte = 00010001
std::cout << myByte.to_string() << '\n'; // Outputs '00010001'
std::cout << myByte.to_ullong() << '\n'; // Outputs '17'
您也可以通过标准数组符号访问该位集。 顺便说一句,我显示的第二个转换(to_ullong)转换为无符号long long,我相信其最大值为18,446,744,073,709,551,615。 如果您需要更大的价值,祝您好运!
只要迭代(向后) vector<bool>
并在迭代器为true时累积相应的值即可:
int base10(const std::vector<bool> &value)
{
int result = 0;
int bit = 1;
for (vb::const_reverse_iterator b = value.rbegin(), e = value.rend(); b != e; ++b, bit <<= 1)
result += (*b ? bit : 0);
return result;
}
现场演示 。
谨防! 这段代码仅供参考,如果值很大,则需要注意int溢出。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.