从2个部分正确打印出整数

时间:2011-05-25 20:36:48

标签: c++ biginteger outputstream objectoutputstream uint

我有一个uint128_t类,将其值存储为uint64_t UPPER, LOWER;,我不知道如何重载operator<<,以便在我传入std::cout时,值将以十进制正确打印。目前,我正在做

std::ostream & operator<<(std::ostream & stream, uint128_t const & rhs){
    if (rhs.upper())                  // if the upper value has a non-zero digit
        stream << rhs.upper();

    // i need some way to pad this so that the number of 0s between 
    // upper and lower is correct

    stream << rhs.lower();
    return stream;

我该怎么办?

编辑:

示例:

如果uint128_t变量有UPPER = 1LOWER = 1,我希望该流包含小数值(1 << 64) + 1

1 个答案:

答案 0 :(得分:1)

假设您已正确实施了除法运算符和模数运算符,则可以执行以下操作:

std::ostream & operator<<(std::ostream & stream, uint128_t const & rhs){

    if(rhs.upper() == 0)
        return stream << rhs.lower();

    char buffer[50];
    char *cp = buffer + 49;
    *cp = 0;
    while(rhs > 0)
    {
        --cp;
        *cp = (rhs % 10) + '0';
        rhs /= 10;
    }

    return stream << cp;
}