正确打印出两部分的整数

发布于 2024-11-09 17:46:49 字数 711 浏览 0 评论 0原文

我有一个 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

I have a uint128_t class that stores its values as uint64_t UPPER, LOWER;, and im not sure how to overload the operator<< so that when i pass in std::cout, the value will print in decimal properly. currently, im just doing

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;

what should i do?

edit:

example:

if a uint128_t variable has UPPER = 1 and LOWER = 1, i want the stream to contain the decimal value of (1 << 64) + 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪失控 2024-11-16 17:46:49

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

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;
}

Assuming you have your division operator and your modulus operator properly implemented, you can do this:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文