Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.

laurens

Member Since 23 Apr 2011
Offline Last Active Jan 06 2012 11:45 AM
-----

Topics I've Started

Convert byte[4] to float

09 December 2011 - 09:56 PM

Hello, i am trying to convert a byte array with 4 bytes in it to a float

Since you can't use system.bitconvert.ToSingle() in netduino i tried to make a similar method but without success
these are the following methods i used:

        public static float ToFloat(byte[] buffer)
        {
            return (float)(buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]);
        }

        public static double ToFloat1(byte[] value)
        {
            return (
                value[0] << 0 |
                value[1] << 8 |
                value[2] << 16 |
                value[3] << 24);
        }

        public static unsafe float ToFloat2(byte[] buffer)
        {
            float test = 0;
            fixed (byte* pBuffer = buffer)
            {
                test = *((float*)pBuffer);
            }
            return test;
        }

        public static unsafe float ToFloat3(ref byte[] buffer)
        {
            uint value = Utility.ExtractValueFromArray(buffer, 0, 4);
            return *((float*)&value);

        }

        public static unsafe float ToFloat4(byte[] value)
        {
            int i = (int)Utility.ExtractValueFromArray(value, 0,4);
            return *(((float*)&i));
        }

I tried the following values:
byte[] buffer = new Byte[4]:
buffer[0] = 118;
buffer[1] = 36;
buffer[2] = 27;
buffer[3] = 193;
float test = System.BitConverter.ToSingle(buffer, 0);

This gives -9,696402 if i use this in a plain C# console project.
I also tried to parse string to a double but this method isn't implemented yet.
Basically I need to transfer a rational number from an arduino to a netduino using a serial connection.
I already programmed the arduino to send the floats as an array of 4 bytes which i then read into a buffer on the netduino.
I checked the bytes in the buffer and they forming the correct number using System.BitConverter.ToSingle(buffer, 0); in a C# console.

Feel free to to make suggestions or
Thanks in advance

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.