Next: units_parse, Previous: Units, Up: Units
The first thing to do is to determine the set of units, and to
declare an enum
to hold the id's. Note that since the
id's are indices into the conversion list, they should be zero-based:
enum { UNIT_parsec, /* 'parsec' */ UNIT_meter, /* 'm', 'meter' */ UNIT_decimeter, /* 'decimeter', 'dm' */ UNIT_centimeter, /* 'centimeter', 'cm' */ UNIT_millimeter, /* 'millimeter', 'mm' */ UNIT_micrometer, /* 'micrometer', 'micron', 'um' */ UNIT_nanometer, /* 'nanometer', 'nm' */ UNIT_Angstrom /* 'A', 'Angstrom', 'angstrom' */ };
Next, create a TokList
structure which holds the names by
which users can refer to the units. Note that this must be in
alphabetical order, and there may be more than one name for a unit.
static TokListToken map[] = { { "A", UNIT_Angstrom }, { "Angstrom", UNIT_Angstrom }, { "angstrom", UNIT_Angstrom }, { "centimeter", UNIT_centimeter }, { "cm", UNIT_centimeter }, { "decimeter", UNIT_decimeter }, { "dm", UNIT_decimeter }, { "m", UNIT_meter }, { "meter", UNIT_meter }, { "micrometer", UNIT_micrometer }, { "micron", UNIT_micrometer }, { "millimeter", UNIT_millimeter }, { "mm", UNIT_millimeter }, { "nanometer", UNIT_nanometer }, { "nm", UNIT_nanometer }, { "parsec", UNIT_parsec }, { "um", UNIT_micrometer } }; TokList map_list = GenTokList( map );
Then, construct a table of conversion factors. These must
be in the same order as your enum
table for the indices to work
correctly.
static UnitConvert convert[] = { { UNIT_parsec, 3.086e19 }, { UNIT_meter, 1000 }, { UNIT_decimeter, 100 }, { UNIT_centimeter, 10 }, { UNIT_millimeter, 1 }, { UNIT_micrometer, 1e-3 }, { UNIT_nanometer, 1e-6 }, { UNIT_Angstrom, 1e-7 }, }; UnitConvertList convert_list = genUnitConvertList( convert );
Finally, construct a UnitList
structure:
UnitList MyUnits = { &convert_list, &map_list };
If you'd like to automate this, see mk_units and
default.units in the suplib/units source directory.
mk_units is a script which reads unit names and conversions from
default.units and generates the header and C
code
for the structures.