Java tutorial
//package com.java2s; import java.math.BigInteger; public class Main { public static int[] generateCompactNaf(BigInteger k) { if ((k.bitLength() >>> 16) != 0) { throw new IllegalArgumentException("'k' must have bitlength < 2^16"); } BigInteger _3k = k.shiftLeft(1).add(k); int digits = _3k.bitLength() - 1; int[] naf = new int[(digits + 1) >> 1]; int length = 0, zeroes = 0; for (int i = 1; i <= digits; ++i) { boolean _3kBit = _3k.testBit(i); boolean kBit = k.testBit(i); if (_3kBit == kBit) { ++zeroes; } else { int digit = kBit ? -1 : 1; naf[length++] = (digit << 16) | zeroes; zeroes = 0; } } if (naf.length > length) { naf = trim(naf, length); } return naf; } private static byte[] trim(byte[] a, int length) { byte[] result = new byte[length]; System.arraycopy(a, 0, result, 0, result.length); return result; } private static int[] trim(int[] a, int length) { int[] result = new int[length]; System.arraycopy(a, 0, result, 0, result.length); return result; } }