Skip to content

Instantly share code, notes, and snippets.

@gabonator
Last active March 11, 2017 15:35
Show Gist options
  • Save gabonator/c9f8dc46c0fb97e9e184042fb0db6549 to your computer and use it in GitHub Desktop.
Save gabonator/c9f8dc46c0fb97e9e184042fb0db6549 to your computer and use it in GitHub Desktop.
Division of two large numbers represented in binary code in js
var shasum = require('crypto').createHash('sha1');
shasum.update(arrCodeBytes);
var arrShaDigest = shasum.digest('buffer');
var arrDigest = new Buffer([arrShaDigest[19-5], arrShaDigest[19-4],
arrShaDigest[19-3], arrShaDigest[19-2], arrShaDigest[19-1], arrShaDigest[19-0]], "binary");
var bits = PushBits(arrCodeBytes, 46).concat(PushBits(arrDigest, 45));
function PushBits(buffer, n)
{
var bits = [];
for (var i=0; i<n; i++)
bits.push(buffer[buffer.length - 1 - Math.floor(i / 8)] & (1<<(i & 7)) ? 1 : 0);
return bits;
}
function DivideBy(bits, n)
{
var remainder = 0;
var result = [];
while (bits.length)
{
remainder = remainder * 2 + bits.pop();
result.push(Math.floor(remainder/n));
remainder %= n;
}
return {remainder: remainder, result:result.reverse(), zero:result.indexOf(1) == -1};
}
function Convert(arr)
{
var result = "";
var t = {zero:false, result:arr};
while (!t.zero)
result = "BCDFGHJKMPQRTVWXY2346789"[(t = DivideBy(t.result, 24)).remainder] + result;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment