Thursday, 5 September 2013

How to safely convert unsigned value to signed?

How to safely convert unsigned value to signed?

As I read, in signed arithmetic there are many cases of undefined
behaviour. Thus, I prefer to calculate results (even signed ones) using
unsigned arithmetic, which is specified without undefined cases.
However, when the result is obtained using unsigned arithmetic, the last
step, the conversion to the signed value remains to be done.
Here is a code I wrote and my question is if the code works in accordance
with the rules, i.e., whether it is safe, not relying on some
undefined/unspecified behaviour?
/*
function to safely convert given unsigned value
to signed result having the required sign
sign == 1 means the result shall be negative,
sign == 0 means the result shall be nonnegative
returns 1 on success, 0 on failure
*/
int safe_convert(unsigned value, int sign, int *result) {
if (sign) {
if (value > -(unsigned)INT_MIN) return 0; // value too big
if (!value) return 0; // cannot convert zero to negative int
*result = INT_MIN + (int)((-(unsigned)INT_MIN) - value);
} else {
if (value > (unsigned)INT_MAX) return 1;
*result = (int)value;
}
return 1;
}
Eventually, is there a way that is simpler, not relying on undefined
behaviour and doing the same thing?

No comments:

Post a Comment