From e8152f454cdeb609db63fbd30317fe177a06cdc8 Mon Sep 17 00:00:00 2001 From: Kirill Fomichev Date: Sun, 10 Jan 2016 15:21:55 +0300 Subject: [PATCH] Update getNAF --- lib/util.js | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/lib/util.js b/lib/util.js index 3db1815..693a89b 100644 --- a/lib/util.js +++ b/lib/util.js @@ -27,14 +27,34 @@ exports.getNAF = function (num, w) { var naf = [] var ws = 1 << w var ws2m1 = (ws << 1) - 1 - for (var k = num.clone(); k.cmpn(0) === 1; k.iushrn(1)) { - var z = 0 - if (k.isOdd()) { - var mod = k.andln(ws2m1) - z = (mod >= ws) ? (ws - mod) : mod - k.isubn(z) + + var k = num.clone() + while (!k.isZero()) { + var i = 0 + for (var d = 1; (k.words[0] & d) === 0 && i < 26; ++i, d <<= 1) { + naf.push(0) + } + + if (i !== 0) { + k.iushrn(i) + } else { + var mod = k.words[0] & ws2m1 + if (mod >= ws) { + naf.push(ws - mod) + k.words[0] -= ws - mod + k.iushrn(1) + } else { + k.words[0] -= mod + naf.push(mod) + if (!k.isZero()) { + for (i = w - 1; i > 0; --i) { + naf.push(0) + } + + k.iushrn(w) + } + } } - naf.push(z) } return naf