简体   繁体   中英

converting c# float to IEEE single precision floating point bytes

I am implementing RFC4506 (XDR) in c#.
Does the binary format for floats in c# ( BitConverter.GetBytes ) use the IEEE standard?

How would I convert a float in c# into the XDR binary format for an IEEE single precision floating point number, I could do the legwork manually, but I would like to know if there is an existing method to do this?

The standard defines the floating-point data type "float" (32 bits or 4 bytes). The encoding used is the IEEE standard for normalized single-precision floating-point numbers [IEEE]. The following three fields describe the single-precision floating-point number:

  S: The sign of the number.  Values 0 and 1 represent positive and
     negative, respectively.  One bit.

  E: The exponent of the number, base 2.  8 bits are devoted to this
     field.  The exponent is biased by 127.

  F: The fractional part of the number's mantissa, base 2.  23 bits
     are devoted to this field.

Therefore, the floating-point number is described by:

     (-1)**S * 2**(E-Bias) * 1.F

the exact layout is as follows.

     +-------+-------+-------+-------+
     |byte 0 |byte 1 |byte 2 |byte 3 |              SINGLE-PRECISION
     S|   E   |           F          |         FLOATING-POINT NUMBER
     +-------+-------+-------+-------+
     1|<- 8 ->|<-------23 bits------>|
     <------------32 bits------------>

Just as the most and least significant bytes of a number are 0 and 3, the most and least significant bits of a single-precision floating- point number are 0 and 31. The beginning bit (and most significant bit) offsets of S, E, and F are 0, 1, and 9, respectively. Note that these numbers refer to the mathematical positions of the bits, and NOT to their actual physical locations (which vary from medium to medium).

.NET uses IEEE representation as well so BitConverter.GetBytes gets you the bytes you need.

It is however a half-baked standard, it only specifies the bit interpretation but does not demand a physical representation. The RFC is infected with Unix preferences from the previous century, like all networking standards are, byte order is big-endian.

On most any machine that can run .NET you need to reverse the bytes. Thus:

public static byte[] XdrFloat(float value) {
    byte[] bytes = BitConverter.GetBytes(value);
    if (BitConverter.IsLittleEndian) Array.Reverse(bytes);
    return bytes;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM