我是c ++的新手。我想使用scanf输入无符号的128位整数,并使用printf打印它。由于我是c ++的新手,我只知道输入输出的这两种方法。有人可以帮我吗?
答案 0 :(得分:3)
您可以使用boost,但必须自行安装此库集:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main()
{
using namespace boost::multiprecision;
uint128_t v = 0;
std::cin >> v; // read
std::cout << v << std::endl; // write
return 0;
}
答案 1 :(得分:0)
如果你想在没有提升的情况下相处,你可以将值存储到两个uint64_t中:
std::string input;
std::cin >> input;
uint64_t high = 0, low = 0, tmp;
for(char c : input)
{
high *= 10;
tmp = low * 10;
if(tmp / 10 != low)
{
high += ((low >> 32) * 10 + ((low & 0xf) * 10 >> 32)) >> 32;
}
low = tmp;
tmp = low + c - '0';
high += tmp < low;
low = tmp;
}
然而,印刷变得更加丑陋:
std::vector<uint64_t> v;
while(high | low)
{
uint64_t const pow10 = 100000000;
uint64_t const mod = (((uint64_t)1 << 32) % pow10) * (((uint64_t)1 << 32) % pow10) % pow10;
tmp = high % pow10;
uint64_t temp = tmp * mod % pow10 + low % pow10;
v.push_back((tmp * mod + low) % pow10);
low = low / pow10 + tmp * 184467440737 + tmp * /*0*/9551616 / pow10 + (temp >= pow10);
high /= pow10;
}
std::vector<uint64_t>::reverse_iterator i = v.rbegin();
while(i != v.rend() && *i == 0)
{
++i;
}
if(i == v.rend())
{
std::cout << 0;
}
else
{
std::cout << *i << std::setfill('0');
for(++i; i != v.rend(); ++i)
{
std::cout << std::setw(8) << *i;
}
}
以上解决方案适用于(包括)
340282366920938463463374516198409551615
= 0x ffff ffff ffff ffff ffff ad06 1410 beff
上面有一个错误。
注意:pow10可以改变,然后需要调整一些其他常数,例如: G。 pow10 = 10
:
low = low / pow10 + tmp * 1844674407370955161 + tmp * 6 / pow10 + (temp >= pow10);
和
std::cout << std::setw(1) << *i; // setw also can be dropped in this case
增加结果以减少打印仍能正常工作的最大数量,减少会增加最大值。当pow10 = 10时,最大值为
340282366920938463463374607431768211425
= ffff ffff ffff ffff ffff ffff ffff ffe1
我不知道最高数字的错误来自哪里,但可能是一些未经考虑的溢出。任何建议表示赞赏,然后我将改进算法。在此之前,我将pow10减少到10并对最高的30个失败数字进行特殊处理:
std::string const specialValues[0] = { /*...*/ };
if(high == 0xffffffffffffffff && low > 0xffffffffffffffe1)
{
std::cout << specialValues[low - 0xffffffffffffffe2];
}
else
{
/* ... */
}
至少,我们可以正确处理所有有效的128位值。