TonyLian 2009-06-05 16:34
浏览 407
已采纳

C# 如何得到float型的Int32的 IEEE 754 浮点值的表示形式

Java中的代码:
[code="java"]
int a = Float.floatToIntBits(123456789012345678901234567890.123456789F);
int b = (int) Double.doubleToLongBits(1234567890123456789012345678901234567890.123456789D);

// a = 1875342472
// b = 61736672
[/code]

就是把float和double在内存中的存储形式,用Int32和Long64表示出来的方法。

[b]问题补充:[/b]
我之前也摸到了BitConverter,但是没找对方法,谢谢。

但是,怎么似乎没有 SingleToInt32Bits 这个方法???
DoubleToInt64Bits倒是有,double已测试测试成功。
还差float。
[b]问题补充:[/b]
我自己找了一段,但是太复杂了,类库里真的没有吗?

[code="java"]
int b = new Int32SingleUnion(f).AsInt32;

    [StructLayout(LayoutKind.Explicit)]
    private struct Int32SingleUnion
    {
        /// <summary>
        /// Int32 version of the value.
        /// </summary>
        [FieldOffset(0)]
        int i;
        /// <summary>
        /// Single version of the value.
        /// </summary>
        [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; }
        }
    }

[/code]

  • 写回答

3条回答 默认 最新

  • fkuebukn 2009-06-05 23:49
    关注

    可以这么用:
    [code="C#"]
    int a = BitConverter.ToInt32(BitConverter.GetBytes(14f), 0);
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?