View previous topic :: View next topic |
Author |
Message |
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
int8 * int8 isn't = int16? |
Posted: Fri Mar 01, 2013 12:27 pm |
|
|
Hello!
one beginner question:
Code: |
int8 var_1 = 100, var_2 = 100;
int16 var_3;
var_3 = var_1 * var_2;
|
Why var_3 isn't equal 10 000?
I need to declare var_1 and var_2 as a long int to obtain 10 000 as an answer. Why? _________________ A person who never made a mistake never tried anything new. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
|
Posted: Fri Mar 01, 2013 2:03 pm |
|
|
understood!
thanks
! _________________ A person who never made a mistake never tried anything new. |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Fri Mar 01, 2013 9:22 pm |
|
|
That has been standard since the K&R creation of the C language. _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Sat Mar 02, 2013 7:08 am |
|
|
Quote: | I need to declare var_1 and var_2 as a long int to obtain 10 000 as an answer. |
No. Just write:
Code: | var_3 = (int16)var_1 * var_2; |
|
|
|
languer
Joined: 09 Jan 2004 Posts: 144 Location: USA
|
|
Posted: Sat Mar 02, 2013 6:04 pm |
|
|
Quote: | I need to declare var_1 and var_2 as a long int to obtain 10 000 as an answer. |
To add to what FVM illustrated. You do not need to "declare" one of the int8 variable as int16, but you need to "cast" it. As said previously when you have int16 = int8 * int8; the order of the operations is int8*int8 = int8 (because both variables are int8) and then the resulting int8 gets promoted ("casted") into an int16. You see where you lost the bits? If one of the two variables you're multiplying is an int16 then the operation will yield an int16. By you explicitly "casting" one of the int8 variables like FVM showed, the result is an int16. This can always get tricky since when dealing with limited memory devices (like MCUs) you're always looking to define variables only as big as they really need to be. So you always have to work the math in your mind to make sure you are not losing resolution (truncating bits) before your final result. |
|
|
|