From 8eee8e5e46c90829776c577d3a1d54ce8863fc54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rory=20O=E2=80=99Kane?= Date: Tue, 5 May 2015 01:15:05 -0400 Subject: [PATCH] Summarize how the implementation works MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This might be of interest to viewers of the project. Especially the “typed array” link, for JavaScript developers who haven’t heard of them. This is copied from my comment at https://lobste.rs/s/sz0ltb/float_js_-_introspect_floating-point_numbers_in_js/comments/uvuwfc#c_uvuwfc, so that everyone can see it, not just other Lobsters users. --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a566cc3..dd873a1 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,17 @@ Math.E.introspect().exponent; // "10000000000" Interactively explore at [http://dherman.github.com/float.js](http://dherman.github.com/float.js). -## License +### How it works + +[Internally](https://github.com/dherman/float.js/blob/master/float.js), this puts the number in a single-element `Float64Array` [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) and gets its `buffer` to read the value’s raw bits: + +```javascript +(new Float64Array([n])).buffer +``` + +Then it converts that buffer to a string of `"1"`s and `"0"`s by viewing the buffer as a `Uint8Array` and mapping each viewed byte to a binary string with `.toString(2)`. Finally, it creates properties like `exponent` and `mantissa` by using `[]` array indexing, `.substring`, and `.slice` to extract the relevant bits. + +### License Copyright © 2012 Dave Herman