16

「32 ビットの符号付き固定小数点数 (16.16)」を float に変換する方法は?

大丈夫(fixed >> 16) + (fixed & 0xffff) / 65536.0ですか?-2.5はどうですか?そして-0.5?

それともfixed / 65536.0正しい方法ですか?

(PS: とにかく、符号付き固定小数点「-0.5」はメモリ内でどのように見えますか?)

4

3 に答える 3

27

2 の補数の 32 ビット整数と演算子は C# のように機能すると想定しています。

変換方法は?

fixed / 65536.0

正しくてわかりやすいです。


(fixed >> 16) + (fixed & 0xffff) / 65536.0

上記の正の整数と同等ですが、速度が遅く、読みにくいです。基本的に、分配法則を使用して 1 つの区分を 2 つの区分に分け、最初の区分をビットシフトを使用して記述します。

負の整数fixed & 0xffffの場合、小数ビットが得られないため、負の数値には正しくありません。

-1にマップする生の整数を見てください-1/65536。このコードは65535/65536代わりに戻ります。


コンパイラによっては、実行する方が速い場合があります。

fixed * (1/65536.0)

しかし、最近のほとんどのコンパイラはすでにその最適化を行っていると思います。

とにかく、符号付き固定小数点「-0.5」はメモリ内でどのように見えますか?

変換を逆にすると、次のようになります。

RoundToInt(float*65536)

設定float=-0.5により、次のようになります-32768

于 2011-12-26T20:14:16.033 に答える
6
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]);
    }
  }

}
于 2012-07-09T09:26:51.687 に答える