J
Jonathan Lee
Hi all,
I have a piece of code which I kindof overlooked that converts a
signed long to an unsigned long plus sign bit. I was just doing this:
unsigned long abs(signed long a) {
unsigned long b;
b = static_cast<unsigned long>(b < 0 ? -b : b);
return b;
}
But then I remember that in two's complement, -b might not exist. For
example, -32768 is representable in a 16-bit two's complement type.
But -(-32768) = 32768 *isn't*.
To make things worse, there are other representations than two's
complement. So I figure the most portable way to find out if I'm out
of range is to check the relative magnitudes of numeric_limits<T>::max
() and min(). But then I've gone in a circle.. if I could check *that*
then I'd have some way of calculating absolute value. :/
Any one got a good idea how to do this cleanly and absolutely
portably? Or should I just add a check for the two's complement
extreme, and trust that the other possibilities are sign/magnitude and
one's complement where the problem won't happen? Should I just leave
those CPUs that use biased representation out? (Not that I can name a
processor that does that... )
--Jonathan
I have a piece of code which I kindof overlooked that converts a
signed long to an unsigned long plus sign bit. I was just doing this:
unsigned long abs(signed long a) {
unsigned long b;
b = static_cast<unsigned long>(b < 0 ? -b : b);
return b;
}
But then I remember that in two's complement, -b might not exist. For
example, -32768 is representable in a 16-bit two's complement type.
But -(-32768) = 32768 *isn't*.
To make things worse, there are other representations than two's
complement. So I figure the most portable way to find out if I'm out
of range is to check the relative magnitudes of numeric_limits<T>::max
() and min(). But then I've gone in a circle.. if I could check *that*
then I'd have some way of calculating absolute value. :/
Any one got a good idea how to do this cleanly and absolutely
portably? Or should I just add a check for the two's complement
extreme, and trust that the other possibilities are sign/magnitude and
one's complement where the problem won't happen? Should I just leave
those CPUs that use biased representation out? (Not that I can name a
processor that does that... )
--Jonathan