fractionToBinaryString.js 845 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var MAX_ITER = 1075; // 1023+52 (subnormals) => BIAS+NUM_SIGNFICAND_BITS-1
  3. var maxBits = 54; // only 53 bits for fraction
  4. module.exports = function fractionToBitString(x) {
  5. var str = '';
  6. if (x === 0) {
  7. return str;
  8. }
  9. var j = MAX_ITER;
  10. var y;
  11. // Each time we multiply by 2 and find a ones digit, add a '1'; otherwise, add a '0'..
  12. for (var i = 0; i < MAX_ITER; i += 1) {
  13. y = x * 2;
  14. if (y >= 1) {
  15. x = y - 1; // eslint-disable-line no-param-reassign
  16. str += '1';
  17. if (j === MAX_ITER) {
  18. j = i; // first 1
  19. }
  20. } else {
  21. x = y; // eslint-disable-line no-param-reassign
  22. str += '0';
  23. }
  24. // Stop when we have no more decimals to process or in the event we found a fraction which cannot be represented in a finite number of bits...
  25. if (y === 1 || i - j > maxBits) {
  26. return str;
  27. }
  28. }
  29. return str;
  30. };