将许多位转换为基数 10

Converting many bits to Base 10

本文关键字:许多位 转换      更新时间:2023-10-16

我正在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) 转换为无符号长整型,我相信它的最大值为 18,446,744,073,709,551,615。 如果您需要比这更大的值,祝你好运!

只需迭代(向后)您的vector<bool>并在迭代器为真时累积相应的值:

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溢出。

希望对您有所帮助。