Annoyance with new integer promotion deprecations

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Feb 6 00:53:48 UTC 2018


On Mon, Feb 05, 2018 at 07:08:12PM -0500, Steven Schveighoffer via Digitalmars-d wrote:
> On 2/5/18 6:56 PM, Adam D. Ruppe wrote:
[...]
> > 2) Change it to:
> >      byte a, b;
> >      int c = a + b;
> > 
> > This is directly analogous to the float example. Which, I agree,
> > reasonable people can disagree on... but I'd be perfectly ok if the
> > `a + b` was still typed `byte` just like above... and the data got
> > discarded when assigned to the `int`.
> 
> I think the CPU has to do extra work to throw away that high bit, no?
[...]

Not sure what you mean by "extra work to throw away that high bit".

If a + b is typed as `byte`, then if an underflow happens the upper bits
will just get thrown away, then the result will be sign-extended to int,
losing the original sign. E.g., 0x80 (-128) + 0xFF (-1) = 0x(1)7F
(underflow, the upper (1) gets discarded), sign-extended to 0x0000007F
(+127).

If a + b was typed as `int` instead, e.g. both a and b were promoted to
int, then the CPU would sign-extend a, sign-extend b, and *then* add the
two together. So 0x80 gets sign-extended to 0xFFFFFF80, and 0xFF gets
sign-extended to 0xFFFFFFFF, and adding the two produces 0xFFFFFF7F
(-129). (There's an overflow 1 at the 33rd bit, but that gets
discarded in 32-bit arithmetic.)


T

-- 
May you live all the days of your life. -- Jonathan Swift


More information about the Digitalmars-d mailing list