View previous topic :: View next topic |
Author |
Message |
Guest
|
Int16 handled as int8 in this ex. |
Posted: Wed Feb 11, 2009 6:12 am |
|
|
This is _only_ a small test program.
Why is "t" printed as a 8bit?
Whats wrong here, is it a compiler bug?
Code: | void x()
{
char str[3]={'5','4','5'};
int16 t;
t = (((str[0]-48)*100) + ((str[1]-48)*10) + (str[2]-48));
printf("%Lu\n",t);
} |
|
|
|
andrewg
Joined: 17 Aug 2005 Posts: 316 Location: Perth, Western Australia
|
|
Posted: Wed Feb 11, 2009 6:40 am |
|
|
The printf is fine. The problem is that all the numbers and variables in the line: Code: | t = (((str[0]-48)*100) + ((str[1]-48)*10) + (str[2]-48)); | are 8 bit (except for the t, which doesn't count for the purposes of evaluating the expression), so the all the math and final result are 8 bit too. At least part of the expression needs to be changed to use 16 bit math.
My recommendation, since you're multiplying, would be to use the _mul() function (see your manual/online help) to achieve that end: Code: | t = _mul(str[0]-48,100) + ((str[1]-48)*10) + (str[2]-48)); | You get both optimal multiply code, plus the 16 bit result you need. _________________ Andrew |
|
|
Wayne_
Joined: 10 Oct 2007 Posts: 681
|
|
Posted: Wed Feb 11, 2009 6:44 am |
|
|
Because str[0] is 8 bit, str[1] is 8bit and str[2] is 8bits.
It is doing 8 bit maths throughout the equation and placing the result in your 16 bit var.
5 * 100 = 500 = 244 (8bit) +
4 * 10 = 40 +
5 = 5
244 + 40 + 5 = 289= 33 (8 bit)
Are you getting the result of 33 ?
My wrap around conversion may be flawed but that is most likely what is happening.
Try putting (int16) before the str values e.g.
((int16)str[0] - 48) * 100 etc |
|
|
Guest
|
|
Posted: Wed Feb 11, 2009 7:20 am |
|
|
Hi
Wayne you are right, adding a cast to int16 solve the problem, but is that normal?
A simple add like this will only work with cast to int16?
Code: | int16 val;
int8 t=5;
.................... val = (t-48)*100;
0CF4: MOVLW 30
0CF6: SUBWF t,W
0CF8: MULLW 64
0CFA: MOVF PRODL,W
0CFC: CLRF val+1 <- Here it clear!
0CFE: MOVWF val
....................
.................... val = (int16)(t-48)*100;
0D00: MOVLW 30
0D02: SUBWF t,W
0D04: CLRF @@x85
0D06: MOVWF @@x84
0D08: MOVFF @@85,??65535+1
0D0C: MOVWF ??65535
0D0E: CLRF @MUL1616.P1+1
0D10: MOVLW 64
0D12: MOVWF @MUL1616.P1
0D14: RCALL 0CD2
0D16: MOVFF 02,val+1
0D1A: MOVFF 01,val
.................... }
0D1E: GOTO 0E6C (RETURN) |
|
|
|
Wayne_
Joined: 10 Oct 2007 Posts: 681
|
|
Posted: Wed Feb 11, 2009 7:32 am |
|
|
Quite normal. |
|
|
|