C#如何将float转换为int [英] c# how to convert float to int

查看:1849
本文介绍了C#如何将float转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将float转换为int(单精度,32位),例如:
'float:2(hex:40000000)to int:1073741824'.知道如何实现吗?
我在msdn帮助中寻找它,但是没有结果.

I need to convert float to int (single precision, 32 bits) like:
'float: 2 (hex: 40000000) to int: 1073741824'. Any idea how to implement that?
I was looking for it in msdn help but with no result.

推荐答案

如果您的目标版本低于.Net 4,而BitConverter不可用,或者要将浮点数转换为32位整数,请使用内存流:

If your aiming for versions less than .Net 4 where BitConverter isn't available, or you want to convert floats to 32 bit ints, use a memory stream:

using System;
using System.IO;

namespace Stream
{
  class Program
  {
    static void Main (string [] args)
    {
      float
        f = 1;

      int
        i;

      MemoryStream
        s = new MemoryStream ();

      BinaryWriter
        w = new BinaryWriter (s);

      w.Write (f);

      s.Position = 0;

      BinaryReader
        r = new BinaryReader (s);

      i = r.ReadInt32 ();

      s.Close ();

      Console.WriteLine ("Float " + f + " = int " + i);
    }
  }
}

虽然缠绕有点长.

这篇关于C#如何将float转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆