Java UUID to Byte Array uuidToBase58(UUID uuid)

Here you can find the source of uuidToBase58(UUID uuid)

Description

uuid To Base

License

Mozilla Public License

Declaration

public static String uuidToBase58(UUID uuid) 

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 w  w .j a v  a 2s. c om*/
 * 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.nio.*;
import java.util.*;
import java.math.BigInteger;

public class Main {
    public static final String DIGITS_58 = "23456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    public static String uuidToBase58(UUID uuid) {
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        BigInteger number = new BigInteger(bb.array()).abs();
        return encode58(number);
    }

    public static String encode58(BigInteger number) {
        return encode(number, DIGITS_58);
    }

    /**
     * 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. uuidToByteArray(UUID uuid)
  2. uuidToBytes(UUID id)
  3. uuidToBytes(UUID uuid)
  4. uuidToBytes(UUID uuid)