C++ Logo

sg12

Advanced search

Re: [ub] Signed shifting

From: Howard Hinnant <howard.hinnant_at_[hidden]>
Date: Mon, 17 Nov 2014 16:59:37 -0500
On Nov 17, 2014, at 4:31 PM, Jens Maurer <Jens.Maurer_at_[hidden]> wrote:

> On 11/17/2014 10:03 PM, John Spicer wrote:
>>
>> On Nov 17, 2014, at 3:57 PM, Gabriel Dos Reis <gdr_at_[hidden] <mailto:gdr_at_[hidden]>> wrote:
>>
>>> Agreed, and that is the easier part :-)
>>>
>>> I’m trying to find a middle-ground for people to get certainty (the implementation will tell you programmatically what the encoding is), while removing or reducing the surface area of undefined behavior. My suspicion is that we will end up with 2’s complement for most cases. But that is not based on a scientific study.
>
>> We could define shifting of signed values to work as-if on a twos-complement system.
>
> There are related core issues 1857, 1861, 1943.
>
> In order to resolve some of these, I'm on the verge of specifying that
> shifts do multiplication / division by 2^N.
>
> Assuming we make shifts for signed numbers well-defined, is the 2^N
> approach any different from specifying as-if two's complement?
>
> (Yes, N < bit-width of type is a requirement.)

#include <iostream>

int
ars(int x, int n)
{
    return x >> n;
}

int
divby2n(int x, int n)
{
    return x / (1 << n);
}

void
test_right(int x, int n)
{
    std::cout << "ars (" << x << ", " << n << ") = " << ars(x, n) << '\n';
    std::cout << "divby2n(" << x << ", " << n << ") = " << divby2n(x, n) << '\n';
}

int
main()
{
    test_right(-3, 1);
}

ars (-3, 1) = -2
divby2n(-3, 1) = -1


Howard

Received on 2014-11-17 22:59:41