View previous topic :: View next topic |
Author |
Message |
Darryl Groom Guest
|
Convert float to long int |
Posted: Fri Aug 01, 2003 2:34 am |
|
|
Does anybody have a decent routinr to convert a 32-bit floating point number back to a 16-bit lon integer?
___________________________
This message was ported from CCS's old forum
Original Post ID: 144516544 |
|
|
IK1WVQ Guest
|
re |
Posted: Fri Aug 01, 2003 3:58 am |
|
|
<font face="Courier New" size=-1>:=Does anybody have a decent routinr to convert a 32-bit floating point number back to a 16-bit lon integer?
simply:
float a=123.89;
int16 b;
b = (int16)float; // its all!!!
====
the value of A must not be greater than 0xffff, off course!!
regards..
</font>
___________________________
This message was ported from CCS's old forum
Original Post ID: 144516546 |
|
|
Sherpa Doug Guest
|
Re: Convert float to long int |
Posted: Fri Aug 01, 2003 6:43 am |
|
|
:=Does anybody have a decent routinr to convert a 32-bit floating point number back to a 16-bit lon integer?
What is wrong with casting?
float f;
long i:
i = (long)f;
___________________________
This message was ported from CCS's old forum
Original Post ID: 144516547 |
|
|
R.J.Hamlett Guest
|
Re: re |
Posted: Fri Aug 01, 2003 10:55 am |
|
|
:=<font face="Courier New" size=-1>:=Does anybody have a decent routinr to convert a 32-bit floating point number back to a 16-bit lon integer?
:=
:=simply:
:=
:=float a=123.89;
:=int16 b;
:=
:=b = (int16)float; // its all!!!
:=
:=====
:=
:=the value of A must not be greater than 0xffff, off course!!
:=
:=regards..
The 'downside' of the cast, is that it can give problems, when dealing with numbers beyond the maximum range of the smaller type. I used the following, when I had to have a 'friendly' handling of this behaviour:
union lblock {
unsigned int16 ui[2];
signed int16 i[2];
int8 b[4];
signed int32 word;
};
//Trims an incoming 32bit value to a 16bit value
signed int16 trim16(union lblock val) {
if (val.b[3] & 0x80) {
//Here -ve
if ((val.ui[1] != 0xFFFFl) || !(val.b[2] & 0x80))
val.word=0xffff8000l;
}
else {
if ((val.ui[1]) || (val.b[2] & 0x80)) val.word=0x7FFFl;
}
return(val.i[1]);
}
Call the function with a normal signed int32, as the variable (the 'union', allows the individual bytes to be accessed internally. This 'trims' anything above the maximum range for the signed int16.
Casting is easier, and quicker, if you know that the range of the incoming value is acceptable.
Best Wishes
___________________________
This message was ported from CCS's old forum
Original Post ID: 144516560 |
|
|
|