View previous topic :: View next topic |
Author |
Message |
ronnarone.r
Joined: 23 Dec 2008 Posts: 12
|
how to convert float to int16? |
Posted: Sat Mar 13, 2010 6:44 am |
|
|
I want to convert float to int16. How to? |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Sat Mar 13, 2010 7:19 am |
|
|
What is wrong with the obvious:
long L;
float F = 12345.6;
L = F;
Should leave L = 12345 _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
Gavin Pinto
Joined: 18 Oct 2009 Posts: 27 Location: Australia
|
|
Posted: Sun Mar 14, 2010 9:55 pm |
|
|
SherpaDoug wrote: | What is wrong with the obvious:
long L;
float F = 12345.6;
L = F;
Should leave L = 12345 |
int16 i;
Cast it
i=(int16)F; _________________ Clear Logic |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19552
|
|
Posted: Mon Mar 15, 2010 3:42 am |
|
|
Both Sherpa Dog's, and Gavin Pinto's answers, do exactly the same thing.
C peforms an automatic 'cast', when variables are assigned to other variables of different types.
Where they would differ, is if you do something 'with' the value on the right of the equation. The explicit cast as shown by Gavin, converts the value 'then and there', into a value of the lower type. The automatic cast, does it at the time the value is put into the variable. Example of the difference:
Code: |
float fpval=1234.56;
int16 ival;
ival=fpval; //ival=1234
ival=(int16)fpval; //ival=1234
ival=fpval*2; //ival=2469 - maths is performed using fp arithmetic,
//since 'fpval' is a float value. 1234.56*2 = 2469.12.
ival=(int16)fpval*2; //ival=2468 - the _integer_ 1234, is multipled by two
//using integer arithmetic (faster), giving 2468.....
|
Best Wishes |
|
|
Gavin Pinto
Joined: 18 Oct 2009 Posts: 27 Location: Australia
|
|
Posted: Mon Mar 15, 2010 6:09 pm |
|
|
In addition I will show how float is stored. It is stored with 32 bits in memory.
Now look at my demonstration below
Example 1
int buff[10];
int32 *fp;
float F =123.45;
fp = &F;
itoa(*fp,16,buff);
puts(buff);
on hyterminal you will see
66E67685
This is bit pattern in memory.
23 bit mantissa, sign bit, 8 bit exponent with bias of 7F
Example 2
int buff[10];
int32 *fp;
float F =123.45E20;
fp = &F;
itoa(*fp,16,buff);
puts(buff);
on hyterminal you will see
534E27C8
This is bit pattern in memory.
23 bit mantissa, sign bit, 8 bit exponent with bias of 7F
Best wishes _________________ Clear Logic |
|
|
|