Opened 7 years ago

Closed 7 years ago

#11999 closed Bugs (fixed)

int128_t from cpp_int gives unexpected results when bitshifting

Reported by: Jordi Vermeulen <J.L.Vermeulen@…> Owned by: John Maddock
Milestone: To Be Determined Component: multiprecision
Version: Boost 1.60.0 Severity: Problem
Keywords: Cc:

Description

The 128-bit signed integer int128_t from cpp_int gives some unexpected results when using the bitshift operator. If I shift the value -1 left by 31 bits, then shift it back right by 32 bits, I get the value -0 instead of -1. I do not encounter this problem with the signed integers of larger size (256, 512, 1024). The code below illustrates the problem. I'm using g++ 5.3.0 on Linux Mint (I can test it with Visual Studio 2015 on Windows 7 later if desired).

To be clear: this only seems to happen when shifting right further than left. If I shift right by 31 they all print -1. It's also not just a bug in the conversion to string: if I multiply by 10, int128_t prints 0, but the rest prints -10.

#include <iostream>
#include <cstdint>
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

int main()
{
    int64_t i0 = -1;
    i0 <<= 31;
    i0 >>= 32;
    std::cout << i0 << std::endl; // prints -1

    int128_t i1 = -1;
    i1 <<= 31;
    i1 >>= 32;
    std::cout << i1 << std::endl; // prints -0

    int256_t i2 = -1;
    i2 <<= 31;
    i2 >>= 32;
    std::cout << i2 << std::endl; // prints -1

    int512_t i3 = -1;
    i3 <<= 31;
    i3 >>= 32;
    std::cout << i3 << std::endl; // prints -1

    int1024_t i4 = -1;
    i4 <<= 31;
    i4 >>= 32;
    std::cout << i4 << std::endl; // prints -1

    return 0;
}

Change History (1)

comment:1 by John Maddock, 7 years ago

Resolution: fixed
Status: newclosed

Fixed in https://github.com/boostorg/multiprecision/commit/2f635b45ffc0517a67e8210239a587a29b62575a

Note however that bit-shifting a signed integer invokes undefined behaviour, so the std::int64_t behaviour above is at the whim of the specific machine/compiler.

Note: See TracTickets for help on using tickets.