These might do a fair chunk of what you need. I've been playing around recently with fixed point math in C using templated classes. It is easier when the precision is the same for both fixed point numbers, but there are calculations for when both fixed point numbers have different precisions and you want the result in a third precision.
Edit: The FixedToInt function went missing, and the IntToFixed function had a typo.
Code:
type
Fixed = Integer;
const
Prec = 12;
function IntToFixed(Value: Integer): Fixed;
begin
IntToFixed := Value shl Prec;
end;
function FixedToInt(Value: Fixed): Integer;
begin
FixedToInt := Value shr Prec;
end;
function FloatToFixed(Value: Single): Fixed;
begin
FloatToFixed := Round(Value * (1 shl Prec));
end;
function FixedToFloat(Value: Fixed): Single;
begin
{ Multiply by 1.0 to convert to floating point before the divide }
FixedToFloat := (Value * 1.0) / ((1 shl Prec) * 1.0);
end;
function FixedAdd(A, B: Fixed): Fixed;
begin
FixedAdd := A + B;
end;
function FixedSub(A, B: Fixed): Fixed;
begin
FixedSub := A - B;
end;
function FixedMul(A, B: Fixed): Fixed;
begin
FixedMul := (A * B) shr Prec;
end;
function FixedDiv(A, B: Fixed): Fixed;
begin
FixedDiv := (A shl Prec) / B;
end;
Bookmarks