Java Base Encode toBase85String(byte[] data)

Here you can find the source of toBase85String(byte[] data)

Description

to Base String

License

Open Source License

Declaration

public static String toBase85String(byte[] data) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   ww  w  .j a  v  a  2 s .  c  om
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

public class Main {
    public static String toBase85String(byte[] data) {
        StringBuffer buffer = new StringBuffer();
        int count = 0;
        for (int i = 0; i <= data.length - 4; i += 4) {
            char[] base85String = toBase85String(getUnsignedInt(data, i));
            buffer.append(base85String);
            count += base85String.length;
            if (count > 80) {
                buffer.append('\n');
                count = 0;
            }
        }
        return buffer.toString();
    }

    private static char[] toBase85String(long data) {
        if (data == 0) {
            return new char[] { 'z' };
        }
        char[] result = new char[5];
        long tempData = data;
        for (int i = 0; i < 5; i++) {
            long number = tempData % 85;
            result[i] = getBase85Char(number);
            tempData = (tempData - number) / 85;
        }
        return result;
    }

    public static long getUnsignedInt(byte[] source, int index) {
        assert (source.length >= index + 4);
        return mergeLong(source[index], source[index + 1], source[index + 2], source[index + 3]);
    }

    private static char getBase85Char(long number) {
        return (char) ('!' + number);
    }

    private static long mergeLong(byte ch1, byte ch2, byte ch3, byte ch4) {
        long i1 = toLong(ch1);
        long i2 = toLong(ch2);
        long i3 = toLong(ch3);
        long i4 = toLong(ch4);
        return ((i1 << 24) + (i2 << 16) + (i3 << 8) + i4);
    }

    private static long toLong(byte b) {
        return 0xff & b;
    }
}

Related

  1. toBase36(int decimalNumber)
  2. toBase36(long l)
  3. toBase36(long num)
  4. toBase62(int decimalNumber)
  5. toBase8(int decimalNumber)
  6. toBase90(int i)