在 OCaml 中,如何从字节数组创建浮点数?
In OCaml, how to create a float from a byte array?
我如何执行类似于此 C 技巧的操作以从字节数组中获取 OCaml float
?
union {
double d;
int i[2];
} u;
u.i[0] = 0;
u.i[1] = -20000000; // u.d = -0x1.ed3p+1005
您或许可以使用 Marshal.from_bytes
。但是,如果您传递的值不是来自 Marshal.to_bytes
,则无法保证您会得到什么。当然,C 代码也有类似的问题。含义未定义(尽管人们仍然使用它)。
您可以使用标准库中的 Int64.float_of_bits
函数:http://caml.inria.fr/pub/docs/manual-ocaml/libref/Int64.html#VALfloat_of_bits。 Int64.bits_of_float
提供反向功能。
您需要按所需顺序将字节打包到 Int64.t
值中。
我如何执行类似于此 C 技巧的操作以从字节数组中获取 OCaml float
?
union {
double d;
int i[2];
} u;
u.i[0] = 0;
u.i[1] = -20000000; // u.d = -0x1.ed3p+1005
您或许可以使用 Marshal.from_bytes
。但是,如果您传递的值不是来自 Marshal.to_bytes
,则无法保证您会得到什么。当然,C 代码也有类似的问题。含义未定义(尽管人们仍然使用它)。
您可以使用标准库中的 Int64.float_of_bits
函数:http://caml.inria.fr/pub/docs/manual-ocaml/libref/Int64.html#VALfloat_of_bits。 Int64.bits_of_float
提供反向功能。
您需要按所需顺序将字节打包到 Int64.t
值中。