I can\'t find the exact specification of how int
value is converted to unsigned long long
in the standard. Various similar conversions, such as int
Unsigned integers have guaranteed modulo arithmetic. Thus any int
value v is converted to the unsigned long
value u such that u = K*2n+v, where K is either 0 or 1, and where n is the number of value representation bits for unsigned long
. In other words, if v is negative, just add 2n.
The power of 2 follows from the C++ standard's requirement that integers be represented with a pure binary system. With n value representation bits the number of possible values is 2n. There is not such a requirement for floating point types (you can use std::numeric_limits
to check the radix of the representation of floating point values).
Also note that in order to cater to some now archaic platforms, as well as one popular compiler that does things its own way, the standard leaves the opposite conversion as undefined behavior when the unsigned value is not directly representable as a signed value. In practice, on modern systems all compilers can be told to make that reverse conversion the exact opposite of the conversion to unsigned type, and e.g. Visual C++ does that by default. However, it's worth keeping in mind that there's no formal support, so that portable code incurs a slight (now with modern computers needless) inefficiency.