Next: , Previous: , Up: Integers   [Contents][Index]


20.1.5 Casting Integers

The right-associative unary operator cast as can be used to derive a new integer value having a different type from an existing value.

For example, this is how we would create a signed 12-bit integer value holding the value 666:

(poke) 666 as int<12>
(int<12>) 666

Note that the 666 literal is originally a 32-bit signed integer. The cast performs the conversion.

Casts between integer types are always allowed, and never fail. If the new type is narrower than the existing type, truncation may be performed to accommodate the value in its new type. For example, the expression 0x8765_4321 as uint<16> evaluates to 0x4321. If the new type is wider than the existing type, either zero-extension or sign-extension is performed depending on the signedness of the operand.

The semantics of the sign-extension operation depends on the signedness of the value being converted, and on the currently selected encoding for negative numbers.

When using two’s complement encoding, converting a signed value will always sign-extend regardless of the signedness of the target type. Thus:

(poke) -2H as uint<32>
0xfffffffeU
(poke) -2H as int<32>
0xfffffffe

Likewise, converting an unsigned value will always zero-extend regardless of the signedness of the target type. Thus:

(poke) 0xffffUH as uint<32>
0xffffU
(poke) 0xffffUH as int<32>
0xffff