majianjia 发表于 2011-10-22 12:09:01

请问在C#里面,如何将四个字节组装成float 类型的数据?

我的下位机发送上了一帧数据里面有 32个字节,
里面包含了几个单精度浮点数据和一些整形。在c#里面,整形可以直接移位组装起来,但是浮点怎么办?我移位的时候他提示我不能移位。
那么我要怎么把四个字节组合成一个float呢?

beixue 发表于 2011-10-22 14:17:21

     // <summary>
      // 将浮点数转ASCII格式十六进制字符串(符合IEEE-754标准(32))
      // </summary>
      // <param name="data">浮点数值</param>
      // <returns>十六进制字符串</returns>
      public static string floatToIntString(float data)
      {
            byte[] intBuffer = BitConverter.GetBytes(data);
            StringBuilder stringBuffer = new StringBuilder(0);
            for (int i = 0; i < intBuffer.Length; i++)
            {
                stringBuffer.Insert(0, toHexString(intBuffer & 0xff, 2));
            }
            return stringBuffer.ToString();
      }


      // <summary>
      // 将ASCII格式十六进制字符串转浮点数(符合IEEE-754标准(32))
      // </summary>
      // <param name="data">十六进制字符串</param>
      // <returns>浮点数值</returns>
      public static float intStringToFloat(String data)
      {
            if (data.Length < 8 || data.Length > 8)
            {
                //throw new NotEnoughDataInBufferException(data.length(), 8);
                throw (new ApplicationException("缓存中的数据不完整。"));
            }
            else
            {
                byte[] intBuffer = new byte;
                // 将16进制串按字节逆序化(一个字节2个ASCII码)
                for (int i = 0; i < 4; i++)
                {
                  intBuffer = Convert.ToByte(data.Substring((3 - i) * 2, 2), 16);
                }
                return BitConverter.ToSingle(intBuffer, 0);
            }

      }

fanwt 发表于 2011-10-22 18:44:04

mark~~

first_blood 发表于 2011-10-22 18:59:18

你别用十六进制传啊,转成字符串

yyccaa 发表于 2011-10-22 19:37:21

BitConverter 类

majianjia 发表于 2011-10-22 23:44:59

回复【3楼】first blood
你别用十六进制传啊,转成字符串
-----------------------------------------------------------------------

没空转呀。。字符串数据量会大好多倍,转换也需要时间。转3个单精度浮点 STM32要用300~500us的时间。我整个系统周期才4ms。调试的时候有十多个浮点数和二十多个整形 字符型要传送。

之后需要转成无线数传,虽然传送的数据会少一些,但是要求最长要在20ms内传完。转成字符串的话,速度不够。

方法大概找到了,还是用copymemory。还没具体试过,头痛住。。

racede 发表于 2011-10-23 00:14:11

回复【5楼】majianjia阿嘉^_^
-----------------------------------------------------------------------

用联合体……

majianjia 发表于 2011-10-23 08:42:56

回复【6楼】racede
回复【5楼】majianjia阿嘉^_^
-----------------------------------------------------------------------
用联合体……
-----------------------------------------------------------------------

C#里面可以用联合体?

racede 发表于 2011-10-23 10:31:15

回复【7楼】majianjia阿嘉^_^
-----------------------------------------------------------------------

FieldOffset
页: [1]
查看完整版本: 请问在C#里面,如何将四个字节组装成float 类型的数据?