0

These lines of code:

long duration; duration = (long)(500*g_sampleTimeInSeconds) / 60; printf("Memory will fill up after %d minutes\n", duration); 

are producing a negative number when g_sampleTimeInSeconds is greater than 65. When g_sampleTimeInSeconds = 65 the printed number is 541 but when it is 66 the printed number is -542 rather then the correct number of 550. This is also the case when g_sampleTimeInSeconds is replaced with hardcoded values.

This code is compiled with the XC8 compiler to run on Microchip PICs

UPDATE:

g_sampleTimeInSeconds is an 16 bit int

4
  • 2
    Please show the data type for g_sampleTimeInSecond Commented Mar 19, 2014 at 16:23
  • 2
    Change to (500L*g_sampleTimeInSeconds) / 60; Commented Mar 19, 2014 at 16:34
  • @chux your method also works - it seems only one of the multiplication operands needs to be cast to a long for this to work Commented Mar 20, 2014 at 8:39
  • 1
    Note: Should add l: printf("Memory will fill up after %ld minutes\n", duration); Commented Mar 20, 2014 at 15:08

1 Answer 1

4

Is this a 16-bit compiler? My guess is that this is a integer conversion issue. where you are exceeding the size of a 16 bit integer, which is being treated as a two's complement number.

So, in your example, you are casting the results of the calculation to a long, after the calculation takes place. Assuming that g_sampleTimeInSeconds is a signed 16-bit int, then

500*66 = 33000, which is larger than the largest positive value of 32767 allowed for a signed 16 bit number. This causes an overflow, and the intermediate value is calculated as 33000 - 65536 = -32536. -32536/60 = -542.xxx.

So, you need to either cast the values within the expression, or change the data type of g_sampleTimeInSeconds to a long.

Sign up to request clarification or add additional context in comments.

2 Comments

Here's all the boring math behind it for those interested.
I'm not in front of the hardware right now so can't test but this makes perfect sense. I didn't realise that the type of g_sampleTimeInSeconds would affect the rest of the calculation like that. I'll accept once fully tested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.