Skip to main content
GameDev.net gamedev.net
🔒 Locked

trusted reciprocal string <-> float conversion

Started by goruka Apr 23, 2011 at 3:18 PM 1 replies 1.2k views
Original Post
goruka
goruka
I'm looking for an algorithm that can represent IEE754 float values and represent them as strings, in such way that after initial first float -> string conversion , subsequent string -> float and float->string conversions remain unaltered, even if some precision has to be lost initially. Any idea where should I look for for this?
thanks!
fastcall22
fastcall22
Does the string need to be human readable? If not, open an stringstream in binary mode, and use stringstream::write to write exactly sizeof(float) bytes of your float into the stream. If the string needs to be human readable, then open an stringstream in text mode and use some of the manipulators (scientific and setprecision, come to mind) before inserting your float.

For reading, keep your stringstream, call stringstream::seekg to set the get position to the beginning of the stream, then to extract your float, use either stringstream::read for binary mode, or plain ol' oerator>> for text mode.

Or maybe I misunderstood your question?
quasar3d
quasar3d
floating point numbers are really just integers, multiplied by 2^e, for some possibly negative exponent e (encoded in a funky way, but just look it up on wikipedia). This means a number can be stored exact if its corresponding fraction has a denominator that is a power of two. This means that if you want to obtain an exact decimal representation, you might need up to e decimal digits behind the dot. If you want to truncate it then you have to make sure that the truncated version still corresponds to a fraction with only powers of 2 in the denominator. If it contains powers of 5 as well, then the binary representation might not terminate (for example, 0.2 = 1/5 equals 0.001100110011... in binary), and so it will be rounded when you try to convert it back to a float.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.