This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Namespace
convert_hex
Public Namespace
Conversion of hex-float representation into an accurate value.
//! Conversion of hex-float representation into an accurate value.//// Derived from golang strconv/atof.go.conststd = @import("std");
constmath = std.math;
constcommon = @import("common.zig");
constNumber = common.Number;
constfloatFromUnsigned = common.floatFromUnsigned;
// converts the form 0xMMM.NNNpEEE.//// MMM.NNN = mantissa// EEE = exponent//// MMM.NNN is stored as an integer, the exponent is offset.pubfnconvertHex(comptimeT: type, n_: Number(T)) T {
constMantissaT = common.mantissaType(T);
varn = n_;
if (n.mantissa == 0) {
returnif (n.negative) -0.0else0.0;
}
constmax_exp = math.floatExponentMax(T);
constmin_exp = math.floatExponentMin(T);
constmantissa_bits = math.floatMantissaBits(T);
constfractional_bits = math.floatFractionalBits(T);
constexp_bits = math.floatExponentBits(T);
constexp_bias = min_exp - 1;
// mantissa now implicitly divided by 2^fractional_bitsn.exponent += fractional_bits;
// Shift mantissa and exponent to bring representation into float range.// Eventually we want a mantissa with a leading 1-bit followed by mantbits other bits.// For rounding, we need two more, where the bottom bit represents// whether that bit or any later bit was non-zero.// (If the mantissa has already lost non-zero bits, trunc is true,// and we OR in a 1 below after shifting left appropriately.)while (n.mantissa != 0andn.mantissa >> (mantissa_bits + 2) == 0) {
n.mantissa <<= 1;
n.exponent -= 1;
}
if (n.many_digits) {
n.mantissa |= 1;
}
while (n.mantissa >> (1 + fractional_bits + 2) != 0) {
n.mantissa = (n.mantissa >> 1) | (n.mantissa & 1);
n.exponent += 1;
}
// If exponent is too negative,// denormalize in hopes of making it representable.// (The -2 is for the rounding bits.)while (n.mantissa > 1andn.exponent < min_exp - 2) {
n.mantissa = (n.mantissa >> 1) | (n.mantissa & 1);
n.exponent += 1;
}
// Round using two bottom bits.varround = n.mantissa & 3;
n.mantissa >>= 2;
round |= n.mantissa & 1; // round to even (round up if mantissa is odd)n.exponent += 2;
if (round == 3) {
n.mantissa += 1;
if (n.mantissa == 1 << (1 + fractional_bits)) {
n.mantissa >>= 1;
n.exponent += 1;
}
}
// Denormal or zeroif (n.mantissa >> fractional_bits == 0) {
n.exponent = exp_bias;
}
// Infinity and range errorif (n.exponent > max_exp) {
returnif (n.negative) -math.inf(T) elsemath.inf(T);
}
varbits = n.mantissa & ((1 << mantissa_bits) - 1);
bits |= @as(MantissaT, @intCast((n.exponent - exp_bias) & ((1 << exp_bits) - 1))) << mantissa_bits;
if (n.negative) {
bits |= 1 << (mantissa_bits + exp_bits);
}
returnfloatFromUnsigned(T, MantissaT, bits);
}
Conversion of hex-float representation into an accurate value.