View previous topic :: View next topic |
Author |
Message |
JerryR
Joined: 07 Feb 2008 Posts: 167
|
Issue with math |
Posted: Mon Jul 28, 2008 6:20 pm |
|
|
I've been looking at the results I get from simple math for an hour and cannot find the reason why I get the results I do. I've broken down the code to its basic elements. The contents of the EEPROM is shown as comments in the code.
Please take a look and tell me where I'm going wrong.
Compiler version 3.249 and code for a PIC18F4520 controller.
Thanks for any help
Code: |
//=============================================================================
//this routine converts SN ASCII strings stored in EE to int32 format for display
SN_TO_INT32()
{
int32 A,B,C,D,E,F,G,H,J; //get this unit's serial number from EE
//EEPROM @ Unit_SN_EEAdr = 0x33 EEPROM Contents
//EEPROM @ Unit_SN_EEAdr+1 = 0x32
//EEPROM @ Unit_SN_EEAdr+2 = 0x33
//EEPROM @ Unit_SN_EEAdr+3 = 0x33
//EEPROM @ Unit_SN_EEAdr+4 = 0x33
//EEPROM @ Unit_SN_EEAdr+5 = 0x33
A = (read_eeprom (Unit_SN_EEAdr)-0x30); //= 3 OK
B= ((read_eeprom (Unit_SN_EEAdr+1)-0x30) * 10); //= 20 OK
C= ((read_eeprom (Unit_SN_EEAdr+2)-0x30) * 100); //= 44 WHAT !
D= ((read_eeprom (Unit_SN_EEAdr+3)-0x30) * 1000); //= 3000 OK
E= ((read_eeprom (Unit_SN_EEAdr+4)-0x30) * 10000); //= 30000 OK
F= ((read_eeprom (Unit_SN_EEAdr+5)-0x30) * 100000); //= 0
G= read_eeprom (Unit_SN_EEAdr+2); //=0x33 OK
H= read_eeprom (Unit_SN_EEAdr+2)-0x30; //=0x03 OK
J= ((read_eeprom (Unit_SN_EEAdr+2)-0x30) * 100); //= 44 *What!
}
|
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Jul 28, 2008 6:44 pm |
|
|
The read_eeprom() function returns a byte, and 100 is contained within
a byte. The compiler thinks you are doing 8-bit math and it doesn't
automatically promote it to 16-bit math. The solution is to tell the
compiler to use 16-bit math by casting one of the operands to 16-bit.
You can do this most easily by appending an 'L' to the 100. |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
Math |
Posted: Tue Jul 29, 2008 5:57 am |
|
|
Hi PCM:
I hope I can call you by your first name I appreciate your reply. I wonder why the correct answer appears in variables D anf F? If it hadn't I certainly would have tried casting.
Thanks again! |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Tue Jul 29, 2008 6:50 am |
|
|
Because 1000 and 10000 are 16 bit constants, so the compiler uses 16 bit math. 100 is a valid 8 bit value so 8 bit math is used. _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
JerryR
Joined: 07 Feb 2008 Posts: 167
|
Math |
Posted: Tue Jul 29, 2008 7:38 am |
|
|
SherpaDoug:
OK, now that makes sense! No casting required on the equations with int32 varables.
I guess I need to cast EVERYTHING when using mixed length variable / constant.
Good lesson, thanks. |
|
|
|