]> git.r.bdr.sh - rbdr/dotfiles/blob
eecda5654dad5130d16b270e7a0fa02b73fb7c1b
[rbdr/dotfiles] /
1 // Credit: https://github.com/paulmillr/es6-shim/
2
3 'use strict';
4
5 var abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min
6 , pow = Math.pow, LN2 = Math.LN2
7 , roundToEven;
8
9 roundToEven = function (n) {
10 var w = floor(n), f = n - w;
11 if (f < 0.5) return w;
12 if (f > 0.5) return w + 1;
13 return w % 2 ? w + 1 : w;
14 };
15
16 module.exports = function (v, ebits, fbits) {
17 var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes;
18
19 // Compute sign, exponent, fraction
20 if (isNaN(v)) {
21 // NaN
22 // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
23 e = (1 << ebits) - 1;
24 f = pow(2, fbits - 1);
25 s = 0;
26 } else if (v === Infinity || v === -Infinity) {
27 e = (1 << ebits) - 1;
28 f = 0;
29 s = (v < 0) ? 1 : 0;
30 } else if (v === 0) {
31 e = 0;
32 f = 0;
33 s = (1 / v === -Infinity) ? 1 : 0;
34 } else {
35 s = v < 0;
36 v = abs(v);
37
38 if (v >= pow(2, 1 - bias)) {
39 e = min(floor(log(v) / LN2), 1023);
40 f = roundToEven(v / pow(2, e) * pow(2, fbits));
41 if (f / pow(2, fbits) >= 2) {
42 e = e + 1;
43 f = 1;
44 }
45 if (e > bias) {
46 // Overflow
47 e = (1 << ebits) - 1;
48 f = 0;
49 } else {
50 // Normal
51 e = e + bias;
52 f = f - pow(2, fbits);
53 }
54 } else {
55 // Subnormal
56 e = 0;
57 f = roundToEven(v / pow(2, 1 - bias - fbits));
58 }
59 }
60
61 // Pack sign, exponent, fraction
62 bits = [];
63 for (i = fbits; i; i -= 1) {
64 bits.push(f % 2 ? 1 : 0);
65 f = floor(f / 2);
66 }
67 for (i = ebits; i; i -= 1) {
68 bits.push(e % 2 ? 1 : 0);
69 e = floor(e / 2);
70 }
71 bits.push(s ? 1 : 0);
72 bits.reverse();
73 str = bits.join('');
74
75 // Bits to bytes
76 bytes = [];
77 while (str.length) {
78 bytes.push(parseInt(str.substring(0, 8), 2));
79 str = str.substring(8);
80 }
81 return bytes;
82 };