Convert from IBM floating point to IEEE floating point standard and Vice Versa- In C#?

前端 未结 4 1466
慢半拍i
慢半拍i 2020-12-06 13:10

Was looking for a way to IEEE floating point numbers to IBM floating point format for a old system we are using.

Is there a general formula we can use in C# to this

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 13:55

    Using first answer I added the following that may be useful in some cases:

    ///

      /// Converts an IEEE floating number to its string representation (4 or 8 ascii codes).
        /// Useful for SAS XPORT files format.
        /// 
        /// IEEE number
        /// When true, output is 8 chars rather than 4
        /// Printable string according to hardware's endianness
        public static string Float2IbmAsAsciiCodes(float from_, bool padTo8_ = true)
        {
            StringBuilder sb = new StringBuilder();
            string s;
            byte[] bytes = BitConverter.GetBytes(Float2Ibm(from_)); // big endian order
    
            if (BitConverter.IsLittleEndian)
            {
                // Revert bytes order
                for (int i = 3; i > -1; i--)
                    sb.Append(Convert.ToChar(bytes[i]));
                s = sb.ToString();
                if (padTo8_)
                    s = s.PadRight(8, '\0');
                return s;
            }
            else
            {
                for (int i = 0; i < 8; i++)
                    sb.Append(Convert.ToChar(bytes[i]));
                s = sb.ToString();
                if (padTo8_)
                    s = s.PadRight(8, '\0');
                return s;
            }
        }
    

提交回复
热议问题