Close

Code: Fixed point output

A project log for reprint: modern printf

reprint is printf redone with decades of hindsight, revamping the semantics and syntax to make a function worthy of Hello World.

analog-twoAnalog Two 04/06/2016 at 20:202 Comments

Fixed point on microprocessors is typically preferred in place of floating point. The Naive programmers can unknowingly encumber their firmware with printf, strtod, and associated if they do not know this. reprint supports fixed point output.

/* Printing to the hundredths place -> "42.042" */
int x = 42042;
reprint("\f3<r", x); 

/* Printing to the hundredths place with printf*/
printf("%u.%03u", x/ 1000, x%1000);

In reprint, we simply load 2 into Register 3 (identified by the "<" character). This is the amount we shift the decimal point to the left. When printing this requires no extra calculation. Oh, and if the 2 is omitted, the shift factor is specified as part of the varargs.

In printf, we much calculate 2 separate values, a division by a 100 and a remainder, in order to split up our source value into the integral and fractional part. We must also remember to zero pad the second number so the leading zeros show up.

Which one do you think is simpler?

Discussions

Analog Two wrote 04/07/2016 at 15:23 point

Yeah, I would always forget the zero pad myself in printf. And thanks for the skull!

  Are you sure? yes | no

Eric Hertz wrote 04/07/2016 at 03:52 point

Dig it. Besides being cleaner to look at, it's also less computationally-intensive!

  Are you sure? yes | no