4 ms·
Hanson and Fraser's example can be improved: if (i >= 0) u = (unsigned)i; else u = -(unsigned)i; This doesn't assume 2's complement - it works
by caf 15y ago
Hanson and Fraser's example can be improved:
if (i >= 0)
u = (unsigned)i;
else
u = -(unsigned)i;
This doesn't assume 2's complement - it works based on C's defined rules for wrapping arithmetic in unsigned types (out-of-range results are brought into range by repeatedly adding or subtracting UINT_MAX + 1).
- psykotic 15y agoYeah, I had a conversation a few weeks ago with a coworker where he misremembered that as being what was in the lcc book. I actually posted about this here (including an excerpt from Steele and Harbinson) ten days ago: http://news.ycombinator.com/item?id=2935583 http://news.ycombinator.com/item?id=2935583. I notice my description there was slightly bungled since I forgot that after the cast for negative integers you of course have to do an unsigned negation (otherwise -1 would be mapped to UINT_MAX, for example).