Eci*_*ana 14 floating-point fixed-point
如何将"32位有符号定点数(16.16)"转换为浮点数?
是否(fixed >> 16) + (fixed & 0xffff) / 65536.0确定?-2.5怎么样?和-0.5?
还是fixed / 65536.0正确的方法?
(PS:无论如何,签名定点"-0.5"在内存中是怎样的?)
Cod*_*aos 22
我假设两个补码32位整数和运算符在C#中工作.
fixed / 65536.0
Run Code Online (Sandbox Code Playgroud)
是正确的,易于理解.
(fixed >> 16) + (fixed & 0xffff) / 65536.0
Run Code Online (Sandbox Code Playgroud)
相当于上面的正整数,但更慢,更难阅读.您基本上使用分布式法则将单个分区分成两个分区,并使用bitshift编写第一个分区.
对于负整数fixed & 0xffff,不会给出小数位,因此负数不正确.
查看-1应该映射到的原始整数-1/65536.此代码返回65535/65536.
根据您的编译器,可能会更快:
fixed * (1/65536.0)
Run Code Online (Sandbox Code Playgroud)
但我认为大多数现代编译器已经进行了优化.
反转转换给我们:
RoundToInt(float*65536)
Run Code Online (Sandbox Code Playgroud)
设置float=-0.5给了我们:-32768.
class FixedPointUtils {
public static final int ONE = 0x10000;
/**
* Convert an array of floats to 16.16 fixed-point
* @param arr The array
* @return A newly allocated array of fixed-point values.
*/
public static int[] toFixed(float[] arr) {
int[] res = new int[arr.length];
toFixed(arr, res);
return res;
}
/**
* Convert a float to 16.16 fixed-point representation
* @param val The value to convert
* @return The resulting fixed-point representation
*/
public static int toFixed(float val) {
return (int)(val * 65536F);
}
/**
* Convert an array of floats to 16.16 fixed-point
* @param arr The array of floats
* @param storage The location to store the fixed-point values.
*/
public static void toFixed(float[] arr, int[] storage)
{
for (int i=0;i<storage.length;i++) {
storage[i] = toFixed(arr[i]);
}
}
/**
* Convert a 16.16 fixed-point value to floating point
* @param val The fixed-point value
* @return The equivalent floating-point value.
*/
public static float toFloat(int val) {
return ((float)val)/65536.0f;
}
/**
* Convert an array of 16.16 fixed-point values to floating point
* @param arr The array to convert
* @return A newly allocated array of floats.
*/
public static float[] toFloat(int[] arr) {
float[] res = new float[arr.length];
toFloat(arr, res);
return res;
}
/**
* Convert an array of 16.16 fixed-point values to floating point
* @param arr The array to convert
* @param storage Pre-allocated storage for the result.
*/
public static void toFloat(int[] arr, float[] storage)
{
for (int i=0;i<storage.length;i++) {
storage[i] = toFloat(arr[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)