How do languages โ€‹โ€‹handle poster printing under the hood?

As a personal project, I am writing a compiler for my own C-like language to orient the processor emulator of my own design.

As part of this, I want to implement a standard floating point library (typical IEEE single precision), but I'm struggling to come up with a way to print the floats in a readable way (like in 1.2345 and not an integer of raw data), the best I I thought - this is to generate values โ€‹โ€‹for log 10 2 and do some odd multiplications to get a number in a suitable form for printing. A.

Is there an algorithm for converting a float into an easily printable form or for printing a float that can be implemented without using printf("%f",float_value); or like castings in a C-like language?

+7
c decimal floating-point algorithm low-level
source share
2 answers

As I understand it, the current state of printing floating point numbers is the Grisu family of algorithms, Florian Loich. You can read the article here .

For easier understanding of problems when converting binary floating point to decimal (and vice versa), I highly recommend Rick Regan's website, http://www.exploringbinary.com/

+6
source share

It may be a dirty function hack, but you can use it as a basis for displaying floating point numbers correctly. It does not use any other helper function other than putchar to actually print something, and it does not cover all situations (for example, your number is NaN or even negative!), But, well, it's just a starting point

 #include <stdio.h> void printfloat (float n) { int whole = n; int power = 1; int digit; /* Find out the largest divisor for printing the integer part */ while (whole>=1) { whole /= 10; power *= 10; } power /= 10; /* Prints the integer part of the number */ whole = n; while (power>=1) { digit = whole/power; whole %= power; putchar ('0'+digit); power /= 10; } /* Prints the decimal point */ putchar ('.'); /* And now the fractional part */ n = n-(int)n; while(n!=0) { digit = n*10; putchar ('0'+digit); n*=10; n = n-(int)n; } putchar ('\n'); } int main() { float n = 123.45678; printfloat(n); return 0; } 

You can check it out here: http://goo.gl/V4pgNZ

+3
source share

All Articles