tadeuzagallo
11/4/2013 - 10:25 AM

Float 64 To Binary String in 135 bytes

Float 64 To Binary String in 135 bytes

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

Float64ToBinaryString


Returns a string representation of the bits in a given Float 64, Expample:

> float2bin(-1234.5678);
  "1100000010010011010010100100010101101101010111001111101010101101"

My first approach was

function(a){
  var b=''+a<0?((a=-a)&&1):0,
      c=Math,
      d=~~c.floor(c.log(a)/c.log(2)),
      e;

  b+=(1e15+(d+1023).toString(2)).slice(-11);
  a-=c.pow(2,d);
  for(;b.length<64;)
    e=c.pow(2,--d),
    b+=e<=a?(a-=e)&0||1:0;
  return b;
};

But was too long so after watch @bartaz talk on jsconf I switched to ArrayBuffer and DataView

function(a,b,c){
  b=new DataView(new ArrayBuffer(8));
  b.setFloat64(0,a);
  for(c=8,a='';c--;)
    a=(1e9+b.getUint8(c).toString(2)).slice(-8)+a;
  return a
}

It was still too long so I came up with the final version with bitwise operators

function(a,b,c){
  b=new DataView(new ArrayBuffer(8));
  b.setFloat64(0,a);
  for(a='',c=64;c--;)
      a=(b.getUint8(c/8)&1<<(7-c%8)?1:0)+a;
  return a
}
function(a, // Float input
         b, // DataView placeholder
         c  // Counter
        ){
  b=new DataView(new ArrayBuffer(8)); // Initialize DataView with 8 bytes ArrayBuffer
  b.setFloat64(0,a); // Set the input float at index 0
  for(c=64, // Set the counter to the max
      a=''; // Reuse a to be the output string
    c--;    // Iterate backwards
     )
    a=(
      b.getUint8(c/8) // Get de integer
      &1<<(7-c%8) // and checks if the bit is on
      ?1:0)+a; // prepend 1 or 0
  return a
}
function(a,b,c){b=new DataView(new ArrayBuffer(8));b.setFloat64(0,a);for(c=64,a='';c--;)a=(b.getUint8(c/8)&1<<(7-c%8)?1:0)+a;return a}
{
  "name": "Float64ToBinaryString",

  "description": "Converts a given float of 64 bits to a string representation of its bits.",

  "keywords": [
    "binary",
    "float",
    "string"
  ]
}
<!DOCTYPE html> 
<title>Float 64 To Binary String</title>
<div>Expected value: <b>1100000010010011010010100100010101101101010111001111101010101101</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
  // write a small example that shows off the API for your example
  // and tests it in one fell swoop.

  var float2bin = function(a,b,c){b=new DataView(new ArrayBuffer(8));b.setFloat64(0,a);for(c=64,a='';c--;)a=(b.getUint8(c/8)&1<<(7-c%8)?1:0)+a;return a};

  document.getElementById( "ret" ).innerHTML = float2bin(-1234.5678);
</script>