Option to make unsigned->signed conversion always well-defined?
Ulf Magnusson
ulfalizer@gmail.com
Thu Oct 6 14:48:00 GMT 2011
On Thu, Oct 6, 2011 at 11:04 AM, Miles Bader <miles@gnu.org> wrote:
> Ulf Magnusson <ulfalizer@gmail.com> writes:
>> Might as well do
>>
>> bool overflowbit(unsigned int a, unsigned int b) {
>> const unsigned int sum = a + b;
>> return (a ^ b) & ~(a ^ sum) & 0x80;
>> }
>>
>> But still not very good output compared to other approaches as expected.
>
> How about:
>
> bool overflowbit2(unsigned int a, unsigned int b)
> {
> const unsigned int sum = a + b;
> return ~(a ^ b) & sum & 0x80;
> }
>
> ?
>
> I thinnnnk it has the same results as your function...
> [I just made a table of all 8 possibilities, and checked!]
>
> -miles
>
> --
> Circus, n. A place where horses, ponies and elephants are permitted to see
> men, women and children acting the fool.
>
Ops, should have been
return ~(a ^ b) & (a ^ sum) & 0x80
~(a ^ b) gives 1 in the sign bit position if the signs are the same,
and (a ^ sum) gives 1 if it's different in the sum.
A clearer way of writing it (that also generates suboptimal code) is
bool overflow(unsigned int a, unsigned int b) {
const unsigned asign = a & 0x80;
const unsigned bsign = b & 0x80;
const unsigned sumsign = (a + b) & 0x80;
return (asign == bsign) && (asign != sumsign);
}
Seems bit-fiddling isn't the way to go.
Maybe I should take this to gnu-help as it isn't really development-related.
/Ulf
More information about the Gcc
mailing list