[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[avr-gcc-list] odd behaviour with type casting
From: |
Paul Thomas |
Subject: |
[avr-gcc-list] odd behaviour with type casting |
Date: |
Thu, 23 Feb 2012 14:47:01 -0700 |
I'm getting very wrong math in one instance using a casting, negative
numbers and a division. If I don't do any 1 of those three things it
works fine. This is with an atxmega32a4 using both the atmel avr-gcc
4.5.1 (avr-gcc (AVR_8_bit_GNU_Toolchain_3.2.3_314) 4.5.1) as well as
4.5.1 gcc built with the script from AvrFreaks. The code snippet to
demonstrate this is:
int16_t var1_16, var2_16, var3_16;
int32_t var1_32, var2_32;
var1_16 = pcpv_data->board.vout;
var2_16 = -48;
var3_16 = ((int32_t)var1_16 * (int32_t)var2_16) / 10;
printf("WRONG: using casting : %d = ( %d *
%d) / 10\n",var3_16, var1_16, var2_16);
var1_16 = -pcpv_data->board.vout;
var2_16 = 48;
var3_16 = ((int32_t)var1_16 * (int32_t)var2_16) / 10;
printf("RIGHT: using casting, positive vars : %d = ( %d *
%d) / 10\n",var3_16, var1_16, var2_16);
var1_16 = pcpv_data->board.vout;
var2_16 = -48;
var3_16 = ((int32_t)var1_16 * (int32_t)var2_16);
printf("RIGHT: using casting, without the division : %d = ( %d *
%d)\n",var3_16, var1_16, var2_16);
var1_16 = -32;
var2_16 = -48;
var3_16 = ((int32_t)var1_16 * (int32_t)var2_16) / 10;
printf("RIGHT: using casting, assigned from constant: %d = ( %d *
%d) / 10\n",var3_16, var1_16, var2_16);
var1_32 = pcpv_data->board.vout;
var2_32 = -48;
var3_16 = (var1_32 * var2_32) / 10;
printf("RIGHT: using int32_t vars : %d = ( %ld *
%ld) / 10\n",var3_16, var1_32, var2_32);
With a result of this:
WRONG: using casting : 13260 = ( -32 * -48) / 10
RIGHT: using casting, positive vars : 153 = ( 32 * 48) / 10
RIGHT: using casting, without the division : 1536 = ( -32 * -48)
RIGHT: using casting, assigned from constant: 153 = ( -32 * -48) / 10
RIGHT: using int32_t vars : 153 = ( -32 * -48) / 10
A section of the .lst file is here:
http://pastebin.com/AMX2Mr75
thanks,
Paul
- [avr-gcc-list] odd behaviour with type casting,
Paul Thomas <=