Hacker News new | past | comments | ask | show | jobs | submit login

You don't need special support from the language, fixed-point arithmetic is effectively the same as integer.

DOOM's implementation of fixed-point is a good example which should work on any platform as long as sizeof(int) >= 4.

https://github.com/id-Software/DOOM/blob/master/linuxdoom-1.... https://github.com/id-Software/DOOM/blob/master/linuxdoom-1....

Addition and subtraction will work normally. Multiplication also works normally except you need to right-shift by FRAC_BITS afterwards (and probably also cast to a larger integer type beforehand to protect against overflow).

Division is somewhat difficult since integer division is not what you want to do. DOOM's solution was to cast to double, perform the division, and then convert that back to fixed-point by multiplying by 1.0 before casting back to integer. This seems like cheating since it's using floating-point as an intermediate type, but it is safe to do because 64-bit floating point can represent all 32-bit integers. As long as you're on a platform with an FPU it's probably also faster than trying to roll your own division implementation.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: