C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: Validity of conversions between 4 byte-like types (byte, char) objects
From: Thiago Macieira (thiago_at_[hidden])
Date: 2019-12-11 14:42:36


On Wednesday, 11 December 2019 10:09:49 PST Roman Babinicz wrote:
> On 11/12/2019 17:26, Thiago Macieira wrote:
> > Pre-C++17:
> > The integer conversions are very well explained in the standard.
> > Converting
> > from signed to unsigned is such that any non-negative values retain their
> > values and any negative ones are represented as TYPE_MAX + 1 -
> > absolute(value).
>
> Thanks,
>
> in e.g. C++14, which points of standard define the negative values as
> above to be converted into TYPE_MAX + 1 - absolute(value) ?

It's the same section of the text ([conv.integral]).

Quoting:
2
 If the destination type is unsigned, the resulting value is the least
unsigned integer congruent to the source integer (modulo 2^n where n is the
number of bits used to represent the unsigned type). [ Note: In a two's
complement representation, this conversion is conceptual and there is no
change in the bit pattern (if there is no truncation). -- end note ]
3
 If the destination type is signed, the value is unchanged if it can be
represented in the destination type; otherwise, the value is implementation-
defined.

> It was my understanding that the converted value in such case depends on
> the binary representation of negative integers, and it would be as you
> written on platforms with 2's complement - but could differ on others.

That used to be the case pre-C++17. C++17 specifies that the conversions
should be implemented as if negative numbers are stored in two's complement.

> C++14 4.7(.2) [conv.integral] mentions what would happen in two's
> complement representation - but that "Note" text seems to only apply to
> situation in which we know that the two's complement is used for the
> signed type.
> And in C++14 that is not guaranteed afaik.
>
> Which is why I thought that for some values it is implementation defined
> what will be the result of assigning signed int into unsigned int.

I don't think there's a point in discussing an older standard. The new one
says it's two's complement and that's all that should matter to you, now and
going forward.

The note is an example, not normative. The normative part is the one that says
it's congruent modulo 2^n.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel System Software Products

STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups