- Home /
convert 16bit float to 16bit int?
What is the correct way to do:
var myfloat = 0.123432;
var myint : int;
myint = myfloat * 32767;
is it a typecast? it's to convert a unity float audio from 0-1 to a 16 bit integer from 0-32767, same as on a CD.
Answer by darkhog · Nov 18, 2014 at 09:05 PM
The correct formula would be round(myfloat*32768)
. To convert back you just divide by 32768. Notice 8 at the end in both cases, it will be more precise as rounding function will (in first case) take care of 0 if result of myfloat*32768 is still smaller than 0.5, it will never actually reach 32768 as floating point precision is unpredictable.
sorry this is the wrong answer, because you tell me how to multiply a float by 32768, while keeping it a float, which is imprecise.
I need to convert a 0-1 float audio wave to a 0-32767 16 bit integer integer variable. ty
Answer by reefwirrax · Dec 04, 2014 at 10:13 PM
Perhaps something like:
floatArr[i] = BitConverter.ToSingle(array, i*4) / 0x80000000;
from http://stackoverflow.com/questions/16078254/create-audioclip-from-byte
Answer by Eric5h5 · Dec 04, 2014 at 10:39 PM
var myFloat = 0.123432;
var myShort : short = System.Convert.ToInt16 (myFloat * 32767);
But given that it's a signed 16-bit number, I'm not sure that's actually right. Maybe it should be:
var myShort : short = System.Convert.ToInt16 (Mathf.Lerp (-32768, 32767, myFloat));
Your answer
Follow this Question
Related Questions
int length control? 3 should be 0003 2 Answers
Cannot convert 'callable(int) as float' to 'float'. 1 Answer
Possible to convert a Float into an Int? 3 Answers
Array - Convert Object into Int 5 Answers
convert GUI.tooltip to int 1 Answer