Convert a float to binary

Hi everyone,

I'm progamming a GPS signal decoder, and I would like to know how to convert the latitude and longitude into binary values to use them in AIS trames.

Then I've got the values comming in a char array, for instance: 827.96573 that I would like to transform as 82796573, to convert it in binary.
Right now I've got a piece of program that gives me a wrong output value considering the last digit of the initial value

temp =100000*(atof(latitude));

Yields to the following results on the console


Anyone gets idea about the problem encountering there ?

Thks, Vincent

You're probably running into a floating point precision problem. Because the float data type uses only 4 bytes, there are a limited number of significant digits it can represent. Generally, a 4-byte float has 6 digits of precision. While it can display more digits than that, any digits after 6 (its precision) are simply the compiler's best guess as to what the data really are. You might have more luck converting it to an unsigned long data type.

Take a look at the TinyGPS library. It converts GPS coordinates into long integers, accurate to one millionth of a degree.

Hi, thank for answering.
I've already consier to use tinyGPS, but Im using signal from a accoustic beacon which is not the same signal. However I don't get your remark that I should use a long unsigned. If I want to convert the char values 04950.22459 into a string 495022459, you mean that I can't use at all atof function.

It would be rather use a loop where I try to suppress the "." from the array char?


yes that is the idea
an unsigned long has 9-10 significant digits (32 bits) where an 32 bit float has only 7 siginificant digits (23 bits)

(the 32 bit float uses 8 bits for exponent and 1 bit for sign)

Yes but a "atol" function takes only the digit before the dot in the array.

Console :


You can always look for the decimal point in the array and throw it away, splice the two pieces together and then convert to a long.

Thank you, at the end I've convert it to a string then use the substring functiun, it mays be not good because of the use of String that everyone is advicing to avoid, but it work for now, i'll try to correct this out later.

Thanks a lot for your advices.