View previous topic :: View next topic |
Author |
Message |
blackpic
Joined: 10 Nov 2011 Posts: 3
|
variable long int problem |
Posted: Thu Nov 10, 2011 8:27 am |
|
|
Hello,
I'm having a problem with a function where a long variable int multiply by 3.
Code: |
long int x;
long int sum;
sum = x * 3;
|
When the value of the variable "x" is 120 for example, the variable "sum" takes a value of 104 when it should be 360.
The variable "sum" always exhibits this problem when it takes values above 250. This variable is 16 bits, then its value is between 0 and 65535, this should not happen. Am I correct?
thanks |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Nov 10, 2011 1:19 pm |
|
|
Post a test program that shows the problem and post your compiler
version. For example, with vs. 4.125, it works. If I run the following
program in MPLAB simulator, I get this output:
Test program:
Code: |
#include <18F452.h>
#fuses XT,NOWDT,PUT,BROWNOUT,NOLVP
#use delay(clock=4M)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
//======================================
void main(void)
{
long int x = 120;
long int sum;
sum = x * 3;
printf("%lu \n\r", sum);
while(1);
} |
|
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Fri Nov 11, 2011 12:21 am |
|
|
You may have redefined the type long. Use int16 for clarity. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Fri Nov 11, 2011 2:50 am |
|
|
There is of course, the other possibility that this is down to how one is displaying the variable.
If this is via something like a 'watch' window, then this needs to be told that sum is a 16bit value. I'd suggest that the watch is set to display an 8bit variable, so is displaying the low byte of the result only. The compiler is working fine, and the result is fine, but you are only looking at part of it....
Note for instance, in PCM_programmers post, how he is _telling_ the compiler to display a long value, with the 'l' in the printf format.
Best Wishes |
|
|
blackpic
Joined: 10 Nov 2011 Posts: 3
|
|
Posted: Sat Nov 12, 2011 8:38 am |
|
|
The problem was solved.
the solution was this:
int X;
long sum;
sum = (long) x * 3;
Thanks to all |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Sat Nov 12, 2011 10:17 am |
|
|
Er.
That is _not_ what you posted.
You had 'x' shown as a long already.
If X is declared as an int, then 'of course' you need to force long arithmetic to be used. Either with a cast, or just by making the constant long.
Code: |
int X;
long sum;
sum = x * 3L;
|
Perhaps the lesson is to type _accurately_ when posting a problem....
Best Wishes |
|
|
blackpic
Joined: 10 Nov 2011 Posts: 3
|
|
Posted: Sun Nov 13, 2011 6:53 pm |
|
|
Thanks Ttelmah. |
|
|
|