Main Site Documentation

Convert double or float to byte array


Hi all

I need to be able to store a double of float value in the battery backed RAM of my ChipworkX module. I only need to store this one value.

As the BatteryRam.write function only accepts a byte array, I can’t figure out how to convert the value to this. In C it was easy with a union. :slight_smile:

I have tried this but I get a type or namespace could not be found at each FieldOffset()

        public struct DoubleUnion
            public double Value;
            public byte Byte0;
            public byte Byte1;
            public byte Byte2;
            public byte Byte3;
            public byte Byte4;
            public byte Byte5;
            public byte Byte6;
            public byte Byte7;

            public byte[] ToByteArray()
                return new[] { Byte0, Byte1, Byte2, Byte3, Byte4, Byte5, Byte6, Byte7 };

            public static byte[] DoubleToBytes(double value)
                return new DoubleUnion { Value = value }.ToByteArray();

            public static float BytesToDouble(byte[] bytes)
                if (bytes.Length != 8) throw new ArgumentException("You must provide eight bytes.");
                return new DoubleUnion { Byte0 = bytes[0], Byte1 = bytes[1], Byte2 = bytes[2], Byte3 = bytes[3],
                                         Byte4 = bytes[4], Byte5 = bytes[5], Byte6 = bytes[6], Byte7 = bytes[7]}.Value;

It looks like I am missing a reference but I can’t find it.


Here’s mine:

public static byte[] GetBytes(float val)
            byte[] buffer = new byte[4];
            return buffer;


Cheers, that worked!

I just had to change to float instead of double but that still has more then enough precision for what I am doing here.


You’re welcome :slight_smile: