public static function getNAF($num, $w)
    {
        $naf = array();
        $ws = 1 << ($w + 1);
        $k = clone($num);

        while( $k->cmpn(1) >= 0 )
        {
            if( !$k->isOdd() )
                array_push($naf, 0);
            else
            {
                $mod = $k->andln($ws - 1);
                $z = $mod;
                if( $mod > (($ws >> 1) - 1))
                    $z = ($ws >> 1) - $mod;
                $k->isubn($z);
                array_push($naf, $z);
            }

            // Optimization, shift by word if possible
            $shift = (!$k->isZero() && $k->andln($ws - 1) === 0) ? ($w + 1) : 1;
            for($i = 1; $i < $shift; $i++)
                array_push($naf, 0);
            $k->iushrn($shift);
        }

        return $naf;
    }