Java BigInteger Calculate encode(BigInteger number, String alphabets)

Here you can find the source of encode(BigInteger number, String alphabets)

Description

Encodes a number using BaseX encoding.

License

Mozilla Public License

Parameter

Parameter Description
number a positive integer
alphabets is the set of alphabet for encoding.

Exception

Parameter Description
IllegalArgumentException if <code>number</code> is negative

Return

a BaseX string

Declaration

public static String encode(BigInteger number, String alphabets) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0.  If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 * //  w  ww .  ja va2s. co m
 * Software distributed under the License is distributed on an "AS IS" basis, 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for 
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is: Jsoda
 * The Initial Developer of the Original Code is: William Wong (williamw520@gmail.com)
 * Portions created by William Wong are Copyright (C) 2012 William Wong, All Rights Reserved.
 *
 ******************************************************************************/

import java.math.BigInteger;

public class Main {
    /**
     * Encodes a number using BaseX encoding.
     *
     * @param number a positive integer
     * @param alphabets is the set of alphabet for encoding.
     * @return a BaseX string
     * @throws IllegalArgumentException if <code>number</code> is negative
     */
    public static String encode(BigInteger number, String alphabets) {
        if (number.compareTo(BigInteger.ZERO) == -1)
            throw new IllegalArgumentException("Number cannot be negative");

        StringBuilder sb = new StringBuilder();
        BigInteger base = BigInteger.valueOf(alphabets.length());
        BigInteger[] divrem = new BigInteger[] { number, BigInteger.ZERO };

        while (divrem[0].compareTo(BigInteger.ZERO) == 1) {
            divrem = divrem[0].divideAndRemainder(base);
            sb.append(alphabets.charAt(divrem[1].intValue()));
        }
        return (sb.length() == 0) ? alphabets.substring(0, 1) : sb
                .reverse().toString();
    }
}

Related

  1. dump(BigInteger x)
  2. dumpBitLengthOfValues(BigInteger... data)
  3. dumpDataPathId(BigInteger datapathId)
  4. dumpNumber(PrintStream out, String s, BigInteger bi)
  5. emit(BigInteger integer)
  6. encode_long(BigInteger big)
  7. encodeBigInt(OutputStream out, BigInteger x)
  8. encodeBigIntNoTypeCode(BigInteger value)
  9. encodeCompactBits(BigInteger value)