C# 等效于(将变量读取为不同类型)

标签 c# c++ variables pointers

我一直在将应用程序的某些部分从 C++ 转换为 C#。有这个编码/解码部分,我需要将变量读取为定义为 uint 的 float :

uint result = 0;

... // a value is set to result

return (*((float *)&result)); // get result as a float value

无论如何要将最后一行转换为 C#?谢谢大家。。

最佳答案

您可以使用不安全的代码来做到这一点 - 或者您可以使用 BitConverter.GetBytes() 将值转换为字节数组,然后使用 BitConverter.ToSingle()转换回来。显然,这效率较低,但如果您处于无法使用不安全代码的情况下,它会起作用。

编辑:我在 MiscUtil 中使用了另一种选择,使用类似 C 的“union ”来更像您的原始示例,但通过自定义结构:

[StructLayout(LayoutKind.Explicit)]
    struct Int32SingleUnion
{
    [FieldOffset(0)]
    int i;

    [FieldOffset(0)]
    float f;

    internal Int32SingleUnion(int i)
    {
        this.f = 0; // Just to keep the compiler happy
        this.i = i;
    }

    internal Int32SingleUnion(float f)
    {
        this.i = 0; // Just to keep the compiler happy
        this.f = f;
    }

    internal int AsInt32
    {
        get { return i; }
    }

    internal float AsSingle
    {
        get { return f; }
    }
}

(当然,你可以对 long 和 double 做同样的事情。)

关于C# 等效于(将变量读取为不同类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139910/

相关文章:

c# - 将数据表加载到数据集中的现有表

python - Python 中的变量复制究竟是如何工作的?

javascript - 在 HTML 中的多个位置显示(和更新)一个不断变化的 JavaScript 变量

c++ - 无法打开包含文件错误但能够找到文件

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c# - 使用列表时如何在 foreach 中使用 CheckBoxFor?

c# - “Code First From Database”模板未显示在 Visual Studio 实体数据模型向导中

c# - 从哪里获得适用于 Windows 的更新 MemCached?

c++ - 错误 C2146 : syntax error : missing ';' before identifier 的可能原因

c++ - std::shared_ptr 和 std::experimental::atomic_shared_ptr 有什么区别?