【问题标题】:Casting an Integer to a Single, preserving bit representation将整数转换为单个保留位表示
【发布时间】:2011-06-25 07:46:23
【问题描述】:

在 VB.NET 中是否有一种快速的方法来获取 32 位 int 并转换为 32 位浮点数,同时保留底层位结构? BitConverter 会这样做,但我想直接转换它而不涉及字节数组。

【问题讨论】:

  • “保留底层位结构”是什么意思,为什么需要它?
  • 我正在使用bit twiddling 来提高瓶颈中的性能,并且我正在为一些功能寻找绝对最快的位破解。

标签: vb.net casting


【解决方案1】:

该死,我怎么可能忘记 C-style Union?

<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Explicit)> _
Public Structure IntFloatUnion
    <Runtime.InteropServices.FieldOffset(0)> Public i As Integer
    <Runtime.InteropServices.FieldOffset(0)> Public f As Single
End Structure


Sub Main()
    Dim u As IntFloatUnion

    u.i = 42
    Console.WriteLine(u.f)

    Console.ReadLine()
End Sub

好吧,用 C# 编写一个类似于 here 所示的辅助函数怎么样:

public static class FancyConverter
{
    public static unsafe float FloatFromBytes(int i)
    {
        return *((float*)(void*)(&i));
    }
}

这可以编译成单独的 dll 并从 VB 项目中引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 2023-03-27
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多