Published
Edited
Nov 29, 2021
1 fork
Importers
3 stars
Insert cell
Insert cell
Insert cell
print_hexfloat(3.141592653589793)
Insert cell
parse_hexfloat('0x1.921fb54442d18p+1')
Insert cell
Insert cell
Insert cell
Insert cell
['+0x1.ff00000000000p+0010', '0x1.ffp10', '0x1ff.0p2', '0x7fc.0p0'].map(parse_hexfloat)
Insert cell
Insert cell
['+0x1.6b00000000000p-1066', '+0x0.000000000016bp-1022'].map(parse_hexfloat)
Insert cell
Insert cell
Insert cell
Insert cell
parse_hexfloat = {
var re = RegExp(`
(?<sign>[+-])?
(?:
(?<inf>Infinity) | (?<nan>NaN) | # for round-trip with print_float
(?<type>0[xX])
(?= [0-9a-fA-F] | \\.[0-9a-fA-F] ) # force at least 1 digit
(?<int>[0-9a-fA-F]*)
(?:\\.(?<frac>[0-9a-fA-F]*))?
(?:[pP]
(?<esign>[+-])?
(?<exp>[0-9]+)
)? # required by the spec, but optional here
)
`.replace(/[#].*$|\s/gm, ''));
return (str) => {
try {
var grp = re.exec(str).groups;
var sign = (grp.sign === '-') ? -1 : 1;
if (grp.nan === 'NaN') return NaN;
if (grp.inf === 'Infinity') return Infinity * sign;
var int = grp.int ? parseInt(grp.int, 16) : 0;
var frac = grp.frac ? parseInt(grp.frac, 16) * 16**(-grp.frac.length) : 0;
var exp = grp.exp ? parseInt(grp.exp, 10) * (grp.esign === '-' ? -1 : 1) : 0;
return sign * (int + frac) * 2 ** exp;
}
catch {
throw new Error(`Invalid hexadecimal float literal: ${str}`);
}
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more