Skip to content

Instantly share code, notes, and snippets.

@usagi
Created April 11, 2012 06:12
Show Gist options
  • Select an option

  • Save usagi/2357298 to your computer and use it in GitHub Desktop.

Select an option

Save usagi/2357298 to your computer and use it in GitHub Desktop.
var binary = {
number_to_string: function(v) {
var r = "";
while ( v >= 2 ) {
var m = v % 2;
r = m + r;
if (m === 1)
v = (v - 1) / 2;
else
v = v / 2;
}
return v + r;
},
string_to_number: function(v) {
var r = 0;
var b = 1;
var m = v.length - 1;
for(var n = 0; n <= m; ++n) {
r = r + v[m - n] * b;
b = b * 2;
}
return r;
},
};
var x = 4;
var c = binary.number_to_string(x);
console.log(c);
var s = binary.string_to_number(c);
console.log(s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment