View previous topic :: View next topic |
Author |
Message |
pfournier
Joined: 30 Sep 2003 Posts: 89
|
32-bit math |
Posted: Mon Jul 13, 2015 8:18 am |
|
|
18f87J60
PCWHD 5.045
PCH 16 bit
I want to do some simple math, but it is escaping me why it is not working. I realize I don't have a native 32bit processor, but I thought the compiler would add the code to do the job.
If I change to all signed 16bit I am limited to about 32 seconds before wrapping.
My other option is to add another timer at 10mS or maybe 100mS, but I still want to understand why this does not work.
Code: |
uint32_t gun32_Timer1Tick_copy, gun32_Timer1Tick;
// gun32_Timer1Tick is incremented by a 1mS timer.
uint32_t gun32_Endpoint;
gun32_Timer1Tick+10000;
//These statements are contained in a larger loop
while (1){
gun32_Timer1Tick_copy=gun32_Timer1Tick;
//Works:
if ( (((signed int16)gun32_Endpoint-(signed int16)gun32_Timer1Tick_copy)<=0)
//Dos not work, falls right through:
if ( (((signed)gun32_Endpoint-(signed)gun32_Timer1Tick_copy)<=0) )
}
|
_________________ -Pete |
|
|
RF_Developer
Joined: 07 Feb 2011 Posts: 839
|
|
Posted: Mon Jul 13, 2015 8:59 am |
|
|
I'm pretty sure casting to (signed) will cast to signed int, not just "cast on" signedness. You need to cast to signed int32. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19590
|
|
Posted: Mon Jul 13, 2015 9:03 am |
|
|
Casting from an unsigned to a signed, is a messy way of doing this. It'll cast 'down', since int32 is not the default size. If you are only using 31bits, then just leave the numbers as signed. However safer way of doing this:
Code: |
if (gun32_Timer1Tick_copy >= gun32_Endpoint)
|
Quicker, safer, and will work for the entire 32bit range..... |
|
|
pfournier
Joined: 30 Sep 2003 Posts: 89
|
|
Posted: Mon Jul 13, 2015 11:27 am |
|
|
Thank you for the responses.
I tried "unsigned int32", but it did not work.
Interestingly, my solution was to cast using "int32_t" instead of "unsigned int32". I am guessing the compiler sees the "unsigned" separately and drops to 8 bits (just that I am seeing).
Ttelmah, the reason I used (a-b)<=0 was from the old days when I used a rabbit processor. Something messed up with wrapping and a>=b would sometimes not work (I can't recall the reason). I imagine the PIC and the compiler are beyond this difficulty.
Thanks.
(I'd like to mark this as solved, but I can't see how?) _________________ -Pete |
|
|
|