View previous topic :: View next topic |
Author |
Message |
ljbdeshler
Joined: 20 Jul 2009 Posts: 1
|
Have to use multiple lines |
Posted: Wed Jan 29, 2014 11:27 am |
|
|
If I type this following into 1 line, I cannot get any results for vmem1 but if I split it up into multiple lines it works. What am I doing wrong?
V4.132
Code: |
sprintf(vm,"%04lu",cntalive);
vmem1 = (int16)(vm[0]-'0') <<12 + (int16)(vm[1]-'0') <<8 + (vm[2]-'0') <<4 + (vm[3]-'0');
|
Code: |
sprintf(vm,"%04lu",cntalive);
vmem1 = (int16)(vm[0]-'0') <<12;
vmem1 += (int16)(vm[1]-'0') <<8;
vmem1 += (vm[2]-'0') <<4;
vmem1 += (vm[3]-'0');
|
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Jan 29, 2014 11:35 am |
|
|
Look at a table of Operator Precedence in C. Which operator is done
first, left-shift or addition ? How can you force operator precedence ?
Answer those questions and you will probably solve your problem. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9229 Location: Greensville,Ontario
|
|
Posted: Wed Jan 29, 2014 11:43 am |
|
|
just a comment: anything that complicated is best done in several lines. Visually you can 'see' how the code should work and is easier to spot problems like PCM P says , precedence, braces, etc.
As well, you should test code like that with known inputs -> outputs to verify that it is correct over the desired range of variables.Don't just test for a couple of cases(like 00 of 0xff) ! You might think it's OK but then 'funny' things happen...
Once you know for sure it works AND you need either more speed or less code space THEN reduce the code, just be sure to test !
hth
jay |
|
|
|