8.03.2011

Number conversion

I always think of string-to-num and num-to-string conversion as sophisticated pieces of code that's not always easy to solve. Strings to integers is simple, as you only need to add and multiplicate. Integers becomes a more math intensive, but it's still very easy to do. But how to do this using floats? That always wondered me. I took a look at an dtoa implementation and geez, this is really creepy lowlevel stuff. Creepy in a way, that there must some simpler and less code-heavy solution. And well, the solution is really simple and I wonder why I didn't notice it before today: split int and fraction part, concatenate with a decimal point - that's all. Equally simple is it to read floats by simply taking two ints and making fraction parts out of them. Very simple I have to say, indeed! So no bitpushing is necessary to archieve it. Did I say I like small code? I like small code.

No comments: