I have been reading some of the LibreOffice code, and there is code that converts from 100mm to twips.
Its basic formula is:
twips = (n>=0) ? (n*72+63) / 127 : (n*72-63) / 127;
Now I know that one twip is 1/20th of a point, and that one inch is 72 points, and 1 inch is 2.54cm, but I cannot work out how the above formula relates to these ratios!
Can anyone shed some light on this?
Putting together what OP provided:
n
is the size in 100 mm.
1 inch is 2.54 cm is 25.4 mm.
inchs = n * 100 / 25.4
or inchs = n / (100 * 25.4)
or inchs = n / 2540
1 inch is 72 points.
points = inchs * 72
1 twip
is 1/20th point.
twips = points / 20
Now, everything together:
twips = n / 2540 * 72 / 20
or twips = n * 72 / 2540 / 20
or twips = n * 72 / 127
If this is done in int
arithmetic there will be truncation instead of mathematical rounding. This can be fixed by adding the half of 127 (127 / 2 = 63
) to n * 72
:
twips = (n * 72 + 63) / 127
This does not handle negative numbers correctly. For these, the 63 has to be subtracted instead:
twips = n >= 0 ? (n * 72 + 63) / 127) : (n * 72 - 63) / 127;
and here we are.
As already pointed out by Ron, the ?:
operator is the ternary if-then-else operator.
An easier to read (but may be less optimized) replacement would be:
if (n >= 0) twips = (n * 72 + 63) / 127);
else twips = (n * 72 - 63) / 127;