Transform an unsigned integer / long into the minimum number of necessary bytes. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Transform an unsigned integer / long into the minimum number of necessary bytes.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        long value = 2;
        System.out.println(java.util.Arrays.toString(toFewestBytes(value)));
    }//w  w w .j  a  va2  s .  co  m

    /**
     * Transform an unsigned integer / long into the minimum number of necessary
     * bytes. This method is only safe to use with positive numbers.
     * @see fromFewestBytes
     */
    public static byte[] toFewestBytes(long value) {

        if (value < 0) {
            throw new IllegalArgumentException("Can't use negative value");
        }
        if (value == 0) {
            return new byte[] { 0 };
        }

        byte[] bytes = fromLong(value);
        int i = 0;
        for (; i < 8; i++) {
            if (bytes[i] != 0) {
                break;
            }
        }
        int len = 8 - i;
        byte[] trimmed = new byte[len];
        System.arraycopy(bytes, i, trimmed, 0, trimmed.length);
        return trimmed;

    }

    /**
     * Print a byte array as a String
     */
    public static String toString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(4 * bytes.length);
        sb.append("[");

        for (int i = 0; i < bytes.length; i++) {
            sb.append(unsignedByteToInt(bytes[i]));
            if (i + 1 < bytes.length) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    /**
     * Converts a 64-bit long into an 8-byte array
     */
    public static byte[] fromLong(long value) {
        byte[] bytes = new byte[8];
        bytes[0] = (byte) ((value >>> 56) & 0xff);
        bytes[1] = (byte) ((value >>> 48) & 0xff);
        bytes[2] = (byte) ((value >>> 40) & 0xff);
        bytes[3] = (byte) ((value >>> 32) & 0xff);
        bytes[4] = (byte) ((value >>> 24) & 0xff);
        bytes[5] = (byte) ((value >>> 16) & 0xff);
        bytes[6] = (byte) ((value >>> 8) & 0xff);
        bytes[7] = (byte) ((value) & 0xff);
        return bytes;
    }

    /**
     * Convert an unsigned byte to an int
     */
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }
}

Related Tutorials