Java Base64 Encode toBase64(long value)

Here you can find the source of toBase64(long value)

Description

Return an optionally single-quoted string containing a base-64 encoded version of the given long value.

License

Apache License

Declaration

public static String toBase64(long value) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**// w w  w  .  ja  v  a  2s  .c o  m
     * Return an optionally single-quoted string containing a base-64 encoded
     * version of the given long value.
     * 
     * Keep this synchronized with the version in Base64Utils.
     */
    public static String toBase64(long value) {
        // Convert to ints early to avoid need for long ops
        int low = (int) (value & 0xffffffff);
        int high = (int) (value >> 32);

        StringBuilder sb = new StringBuilder();
        boolean haveNonZero = base64Append(sb, (high >> 28) & 0xf, false);
        haveNonZero = base64Append(sb, (high >> 22) & 0x3f, haveNonZero);
        haveNonZero = base64Append(sb, (high >> 16) & 0x3f, haveNonZero);
        haveNonZero = base64Append(sb, (high >> 10) & 0x3f, haveNonZero);
        haveNonZero = base64Append(sb, (high >> 4) & 0x3f, haveNonZero);
        int v = ((high & 0xf) << 2) | ((low >> 30) & 0x3);
        haveNonZero = base64Append(sb, v, haveNonZero);
        haveNonZero = base64Append(sb, (low >> 24) & 0x3f, haveNonZero);
        haveNonZero = base64Append(sb, (low >> 18) & 0x3f, haveNonZero);
        haveNonZero = base64Append(sb, (low >> 12) & 0x3f, haveNonZero);
        base64Append(sb, (low >> 6) & 0x3f, haveNonZero);
        base64Append(sb, low & 0x3f, true);

        return sb.toString();
    }

    private static boolean base64Append(StringBuilder sb, int digit, boolean haveNonZero) {
        if (digit > 0) {
            haveNonZero = true;
        }
        if (haveNonZero) {
            int c;
            if (digit < 26) {
                c = 'A' + digit;
            } else if (digit < 52) {
                c = 'a' + digit - 26;
            } else if (digit < 62) {
                c = '0' + digit - 52;
            } else if (digit == 62) {
                c = '$';
            } else {
                c = '_';
            }
            sb.append((char) c);
        }
        return haveNonZero;
    }
}

Related

  1. toBase64(final byte[] bytes)
  2. toBase64(final byte[] value)
  3. toBase64(final String str)
  4. toBase64(int x)
  5. toBase64(long num)
  6. toBase64(String value)
  7. toBase64Impl(byte[] data)
  8. toBase64String(byte[] array)
  9. toBase64String(byte[] data)