Java ByteOrder toInt(byte[] bytes, ByteOrder order)

Here you can find the source of toInt(byte[] bytes, ByteOrder order)

Description

to Int

License

Open Source License

Declaration

public static int toInt(byte[] bytes, ByteOrder order) 

Method Source Code


//package com.java2s;
import java.nio.ByteOrder;

public class Main {
    public static final int COUNT = 4;

    public static int toInt(byte[] bytes, ByteOrder order) {
        if (bytes == null) {
            throw new NullPointerException();
        }//  w  w w. j av a2s  .  com
        byte[] temp = subArray(bytes, 0, COUNT);
        if (temp.length < COUNT) {
            temp = concat(new byte[COUNT - temp.length], temp);
        }

        int result = 0;
        int multiple = 1;
        if (ByteOrder.BIG_ENDIAN.equals(order)) {
            for (int i = COUNT - 1; i >= 0; i--) {
                result += temp[i] * multiple;
                multiple *= 256;
            }
        } else {
            for (int i = 0; i < COUNT; i++) {
                result += temp[i] * multiple;
                multiple *= 256;
            }
        }
        return result;
    }

    public static byte[] subArray(byte[] src, int pos, int length) {
        if (src == null || src.length < length - pos) {
            throw new IllegalArgumentException();
        }
        byte[] result = new byte[length];
        System.arraycopy(src, pos, result, 0, length);
        return result;
    }

    public static byte[] concat(byte[] src1, byte[] src2) {
        byte[] result = new byte[src1.length + src2.length];
        System.arraycopy(src1, 0, result, 0, src1.length);
        System.arraycopy(src2, 0, result, src1.length, src2.length);
        return result;
    }
}

Related

  1. reduceToSmallestByteArray(byte[] originalBytes, ByteOrder byteOrder, boolean isSigned)
  2. setLong(byte[] bytes, int start, int end, long value, ByteOrder byteOrder)
  3. toBytes(int value, ByteOrder order)
  4. toDoubleByteArray(double val, ByteOrder outOrder, byte[] buf, int off)
  5. toFloatByteArray(float val, ByteOrder outOrder, byte[] buf, int off)
  6. toInt16ByteArray(final int val, final ByteOrder outOrder, final byte[] buf, final int off)
  7. toInt64ByteArray(final long val, final ByteOrder outOrder, final byte[] buf)