This question already has an answer here:<ul><li> <a href="/questions/25338897/how-to-convert-float-into-binary-in-c" dir="ltr" rel="nofollow">how to convert float into binary in c#?</a> <span class="question-originals-answer-count"> 1 answer </span> </li> </ul>
I have two float now,say f1 and f2. I want to send them to my micro controller through my computer serial port, how should I do it? My understanding is we need to convert f1 and f2 to binary first,then send to micro, after that cnvert back to float again. So I am confused that HOW DO I CONVERT FLOAT TO BINARY BEFORE I SEND THEM OUT? My code now is
b1 = System.BitConverter.GetBytes(f1); b2 = System.BitConverter.GetBytes(f2);Answer1:
It depends on the endianness of your microcontroller's architecture. But roughly speaking you need to do this:<ol><li>Convert your float to a 4-byte array. You're on the right track, although my C# is very rusty.</li> <li>Send them one by one to the microcontroller</li> <li>
If your microcontroller supports floating point representation you could cast the four-byte array into a float:
byte array; // Pre-allocate your array getBytesFromSerial(array); // Fill the array with values from serial port float converted = 0; memcpy(&converted, array, 4); /** Now "converted" holds the float value */</li> </ol>
Now that will work only if the endianness of your uC is consistent with the order in which you are sending the data. If that doesn't work try sending the byte array in inverted order. And please mind the error checking!