Java Base Encode toBase2SuffixedString(long n)

Here you can find the source of toBase2SuffixedString(long n)

Description

to Base Suffixed String

License

Apache License

Declaration

public static String toBase2SuffixedString(long n) 

Method Source Code

//package com.java2s;
/* /*from   www .jav a  2s .  c o  m*/
 * Copyright 2015 Terracotta, Inc., a Software AG company.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    private static final String[] BASE_2_SUFFIXES = new String[] { "", "K", "M", "G", "T", "P", "E" };

    public static String toBase2SuffixedString(long n) {
        if (n > 0 && Long.bitCount(n) == 1) {
            int i = Long.numberOfTrailingZeros(Math.abs(n)) / 10;
            return (n >> (i * 10)) + BASE_2_SUFFIXES[i];
        } else {
            int i = (63 - Long.numberOfLeadingZeros(n)) / 10;

            long factor = 1L << (i * 10);
            long leading = n / factor;
            long decimalFactor = factor / 10;
            if (decimalFactor == 0) {
                return leading + BASE_2_SUFFIXES[i];
            } else {
                long decimal = (n - (leading * factor)) / (factor / 10);
                return leading + "." + decimal + BASE_2_SUFFIXES[i];
            }
        }
    }
}

Related

  1. toBase16(byte[] data)
  2. toBase16(int[] arr)
  3. ToBase16(StringBuilder str, byte[] data)
  4. toBase2(byte b)
  5. toBase26(int number)
  6. toBase32Char(int i)
  7. toBase36(int decimalNumber)
  8. toBase36(long l)
  9. toBase36(long num)