Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   Operator/Bit Issue (http://www.chiefdelphi.com/forums/showthread.php?t=64937)

1jbinder 23-02-2008 00:47

Operator/Bit Issue
 
Hi,

We are having a really unique problem that has stumped the whole programing team, all of the mentors, and the team leader. We are trying to write some code in MPLab to calculate the number of encoder ticks needed to reach six feet. We have found that fourteen encoder clicks is the same as one inch. The problem comes in when we try to multiply 72(six feet in inches) by 14(clicks in an inch). When this happens we get -16 which is 32 bits off. We are using the variable type long. Below is the code that we have written:

long atemp=0;
atemp=14*72;//should be 1008
printf("atemp=%ld\r\n", atemp);

This code did not work and gave us a value of -16 for atemp. We also tried this:

long atemp=0;
atemp=72+72+72+72+72+72+72+72+72+72+72+72+72+72;
printf("atemp=%ld\r\n", atemp);

This also did not work and gave us a value of -16. Adding smaller numbers works fine and multiplying smaller numbers also works. We have pretty much exhausted any ideas.
Thanks,
Julian

Joe Ross 23-02-2008 00:51

Re: Operator/Bit Issue
 
C18 diverges from the ISO standard in that when all operands will fit in a char, it will do the math in a char. If you cast one operand to an int, it will do the math the way you want. You can also enable integer promotion in the project file.

tdlrali 23-02-2008 01:09

Re: Operator/Bit Issue
 
Or write

Code:

atemp=14L*72L;
which will make sure the numbers are treated as longs.

Also, i'm not sure if you can print longs...

Guy Davidson 23-02-2008 01:13

Re: Operator/Bit Issue
 
Quote:

Originally Posted by tdlrali (Post 705525)
Also, i'm not sure if you can print longs...

I believe that both casting them to an int or using %ld should work.

tdlrali 23-02-2008 01:25

Re: Operator/Bit Issue
 
Quote:

I believe that both casting them to an int or using %ld should work.
int wont print the whole long though (only the low 8 bits), and i can't remember whether %ld actually works.

Racer26 23-02-2008 01:55

Re: Operator/Bit Issue
 
I think %ld does work in later revisions of the default code (kevins?)

Also, an alternative method of getting the math the way you want it:

Code:

atemp = (long)14*(long)72;
Yay for C-style casting... in my opinion, SO much easier than C++ casts.

BornaE 23-02-2008 02:36

Re: Operator/Bit Issue
 
You code is working. The problem is with the printf statement.
so you can keep your code.

1jbinder 23-02-2008 14:30

Re: Operator/Bit Issue
 
Thanks to everyone for the help. Typecasting made the code work. The printf statement was fine.
Julian


All times are GMT -5. The time now is 01:00.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi