将int位转换为浮点位

Hob*_*ist 3 c# bit-manipulation

我正在创建一个缓冲区,它将在横幅中读/写,我可以完全消除TCP分段带来的问题.我遇到的唯一问题是浮点变量,其他一切工作正常,除了浮点数.我找不到有关如何将int32位转换为float的任何信息.

将float转换为int位时,使用以下方法(直接从java的源代码中删除并转换)

private int floatToIntBits(float value)
{
    int result = BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
    if (((result & 0x7F800000) == 0x7F800000) && (result & 0x80000000) != 0)
        result = 0x7fc00000;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

但是,现在我需要做相反的事情,遗憾的是,BitConverter类中没有任何与float一起使用的函数.

我也无法在JavaDocs中找到很多信息,而不是我个人可以使用的任何信息,你可以在这里找到信息.

Abe*_*rro 10

BitConverter 会产生一些开销和不必要的缓冲区。该解决方案几乎与不安全转换一样快:

[StructLayout(LayoutKind.Explicit)]
struct FloatToInt 
{
    [FieldOffset(0)]private float f;
    [FieldOffset(0)]private int i;
    public static int Convert(float value)
    {
        return new FloatToInt { f = value }.i;
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 7

难懂,如果你使用doublelong,有BitConverter.DoubleToInt64BitsBitConverter.Int64BitsToDouble.我真的不知道为什么没有Single/ Int32等效,因为它迫使你byte[]在堆上创建一个无意义的(它甚至不允许你传入一个预先存在的缓冲区).

如果您乐意使用unsafe代码,您实际上可以在简单的数据thunk中完成所有操作,无需任何方法调用或数组:

public static unsafe int SingleToInt32Bits(float value) {
    return *(int*)(&value);
}
public static unsafe float Int32BitsToSingle(int value) {
    return *(float*)(&value);
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*try 5

使用BitConverter.ToSingle方法:

int i = ...;
float f = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
Run Code Online (Sandbox Code Playgroud)