Main Site Documentation

Convert double or float to byte array


#1

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()


[StructLayout(LayoutKind.Explicit)]
        public struct DoubleUnion
        {
            [FieldOffset(0)]
            public double Value;
            [FieldOffset(0)]
            public byte Byte0;
            [FieldOffset(1)]
            public byte Byte1;
            [FieldOffset(2)]
            public byte Byte2;
            [FieldOffset(3)]
            public byte Byte3;
            [FieldOffset(4)]
            public byte Byte4;
            [FieldOffset(5)]
            public byte Byte5;
            [FieldOffset(6)]
            public byte Byte6;
            [FieldOffset(7)]
            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.


#2

Here’s mine:

public static byte[] GetBytes(float val)
        {
            byte[] buffer = new byte[4];
            GHIElectronics.NETMF.System.Util.InsertValueIntoArray(val,buffer,0);
            return buffer;
        }

#3

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.


#4

You’re welcome :slight_smile: