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

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条)

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型