Search code examples
c#arraysfloating-pointieee-754bitconverter

Converting from float (IEEE754) to byte[]


I'm using IEEE754 format to communicate some values via TCP. In this example, I'm converting an int to a byte[], and then using BitConverter to convert it to a float (already in IEEE754 Single format, 32-bits).

I need to take this float and store it into a byte[4], but without going back to its original value (which would not be encoded in the specified format). BitConverter.GetBytes() autommatically does that, which is why I cannot use it.

int volumeInt = (int)(volumeTest);
byte[] volumeTank = new byte[4];

volumeTank[0] = (byte)(volumeInt >> 24);
volumeTank[1] = (byte)(volumeInt >> 16);
volumeTank[2] = (byte)(volumeInt >> 8);
volumeTank[3] = (byte)(volumeInt >> 0);

float volumeFloat = BitConverter.ToSingle(volumeTank, 0);

Any ideas?

EDIT

Context: The reason I'm doing this is to encode the byte[] as ASCII and include it in a string that will be sent via TCP. It has to be in IEEE-754 format, and it has to be encoded in ASCII. Though the answer I was looking for was only how to convert a float to a byte[].

Example:

Given an int : 9876. It can be converted to IEEE754 format as a float: -8.380858E-27. Now, I want this value stored in a byte array, without losing the format and going back to its original value (9876).


Solution

  • Fix the format, let's say you have an agreement about BigEndian. Also here in online hex converter which can help to see the different representation of hex string:

    using System;
    
    public class Program
    {
        public static void Main()
        {
            float f = 9876f;
            var bytes = GetBigEndian(f);
            Console.WriteLine("{0} => {1}", f, BitConverter.ToString(bytes));
            Console.WriteLine("{0} => {1}", f, GetFloatFromBigEndian(bytes));
        }
    
        static byte[] GetBigEndian(float v)
        {
            byte[] bytes = BitConverter.GetBytes(v);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            return bytes;
        }
    
        static float GetFloatFromBigEndian(byte[] bytes)
        {
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes); // We have to reverse
            return BitConverter.ToSingle(bytes, 0);
        }
    }