Hier ist, was der C-Standard dazu zu sagen hat
1 | 6.3 Conversions
|
2 |
|
3 | 6.3.1 Arithmetic operands
|
4 |
|
5 | 6.3.1.3 Signed and unsigned integers
|
6 | 1 When a value with integer type is converted to another integer
|
7 | type other than _Bool, if the value can be represented by the new type,
|
8 | it is unchanged.
|
9 | 2 Otherwise, if the new type is unsigned, the value is converted by
|
10 | repeatedly adding or subtracting one more than the maximum value that
|
11 | can be represented in the new type until the value is in the range
|
12 | of the new type.60)
|
13 | 3 Otherwise, the new type is signed and the value cannot be represented
|
14 | in it; either the result is implementation-defined or an
|
15 | implementation-defined signal is raised.
|
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
Da ein signed long alle Werte eines unsigned short darstellen kann,
kommt 6.3.1.3-1 zum Zug, nachdem sich keine Veränderung im Wert ergibt.
Diese Regelung erfordert mehr oder weniger, dass beim Casten in einen
größeren Datentyp erst mal die Bitgröße angepasst werden muss, ehe dann
eine mögliche Neuinterpretation eines Vorzeichens ins Spiel kommt. In
der Praxis und unter der Annahme einer 2-er Komplement Darstellung bei
signed Datentypen, läuft es in der Praxis beim Casten in einen höheren
Datentyp darauf hinaus
1 | Quelldatentyp ist ein unsigned Typ ?
|
2 | Ja | Nein
|
3 | +-------------+---------------+
|
4 | | |
|
5 | v |
|
6 | hänge entsprechen v
|
7 | viele 0 Bytes links an MSB vom Wert gesetzt?
|
8 | Nein | ja
|
9 | +------+-----------------+
|
10 | | |
|
11 | hänge entsprechend hänge entsprechend
|
12 | viele 0x00 Bytes links viele 0xFF Bytes links
|
13 | an an
|