将许多位转换为基数 10
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) 转换为无符号长整型,我相信它的最大值为 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溢出。
希望对您有所帮助。
相关文章:
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 16 位到 10 位转换代码说明
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- C++中的24位到32位转换
- 将字节数组转换为对象C++ |C++中的 C# 位转换器
- 我把我的编译器从32位转换为64位,但我仍然不能使用超过2GB:(为什么
- 如何将内存中的位转换为一串和零?
- 位操作将最左侧的设置位转换为右侧交替位?
- 内存泄漏,许多位图图像C CLI
- 如何将单个位转换为字符
- 如何在AVX2中从32位转换为16位未签名的整数
- 如何使用OPENCV C 将24位转换为8位深度PNG图像
- 以C++为单位将每 5 位转换为整数值
- 使用位操作将8字节数字中的每个字节中的一位转换为单个字节
- 如何宽色域,从8位转换到10位
- 从 8 位转换为 1 字节
- 是否有任何中间件/库可以将二进制或文本数据从64位转换为32位
- 将许多位转换为基数 10
- 将内存中的 16 位转换为 std::string
- 在MS VC 2013 Express中将C++dll从32位转换为64位