将整数转换为单个,保留位表示 [英] Casting an Integer to a Single, preserving bit representation
本文介绍了将整数转换为单个,保留位表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在VB.NET中有一种快速的方法来获取32位int并转换为32位浮点数,同时保留底层位结构? BitConverter会做到这一点,但是我想直接转换它而不涉及字节数组。
Is there a fast way in VB.NET to take a 32-bit int and cast to a 32-bit float while preserving the underlying bit structure? BitConverter will do this, but I'd like to cast it directly without involving byte arrays.
推荐答案
忘记C风格联盟?
<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#中编写一个类似于此处:
public static class FancyConverter
{
public static unsafe float FloatFromBytes(int i)
{
return *((float*)(void*)(&i));
}
}
这可以编译为单独的dll, VB项目。
This can be compiled to a separate dll and referenced from the VB project.
这篇关于将整数转换为单个,保留位表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文