| > Wouldn’t that last example be incorrect mathematically? For example, if the Int8 was -10 and the UInt16 was 10, what would that casting do? Well.... Signed integer arithmetic and unsigned integer arithmetic do not differ. At all. The difference between an Int16 and a UInt16 is not in the 16 defined bits. It's in the infinite number of implicit bits representing place values above 2^15. Those bits are always 0 for the UInt16, but they're identical with the high bit of the Int16. So it's not clear what it would mean for the result type to be "incorrect mathematically". Mathematically, an Int16 and a UInt16 are the same thing. However, the path by which you promote the values does matter. I don't know what Julia does. But: -10 (Int8) + 10 (UInt16)
-10 (Int16) + 10 (UInt16)
65526 (UInt16) + 10 (UInt16)
0 (UInt16)
is a different result from -10 (Int8) + 10 (UInt16)
246 (UInt8) + 10 (UInt16)
246 (UInt16) + 10 (UInt16)
256 (UInt16)
One of those should be the result Julia gives. I tend to hope it's the first one. That would correspond to a promotion strategy of "always expand the type to its full width before converting between signed and unsigned". Expansion (and shift, I guess) is the only operation for which the difference between signed and unsigned is relevant.> Would a better promotion be Int32 for both? Probably not; that would imply that when you add two UInt16s together, you expect to get a UInt32 (or UInt17...) back. |
Great point on the path dependence.