3 ms·
Minor nit: the result of converting an unsigned integer to signed is implementation-defined if the unsigned value cannot be represented in the destination type.
by stephencanon 13y ago
Minor nit: the result of converting an unsigned integer to signed is implementation-defined if the unsigned value cannot be represented in the destination type. This can be fixed with the following bizarre expression:
*rp = s <= INTN_MAX ? s : (intN_t)(s + INTN_MIN) + INTN_MIN;
"What the hell?” I hear the internet ask. if s <= INTN_MAX, then the result is representable as an intN_t, so we’re fine; otherwise s + INTN_MIN is guaranteed* to be representable as an intN_t, and the second addition of INTN_MIN “completes" the twos-complement (no-op) conversion to signed.
“But you can’t assume that the signed type is twos complement!” an actually of pedants responds. Fortunately, the <stdint.h> intN_t types, if they exist, are required to be twos-complement.
“But more operations and—oh-horrors-a-branch!” say the premature optimizers. Not to fear. Compilers are smart. Both gcc and clang are happy to look through this and no-op the whole thing away.
[*] for the <stdint.h> intN_t types, which are twos-complement with no padding.