Java ByteOrder convertBytesToBigInteger(byte[] bytes, ByteOrder byteOrder, boolean isSigned)

Here you can find the source of convertBytesToBigInteger(byte[] bytes, ByteOrder byteOrder, boolean isSigned)

Description

convert Bytes To Big Integer

License

Apache License

Declaration

public static BigInteger convertBytesToBigInteger(byte[] bytes, ByteOrder byteOrder, boolean isSigned) 

Method Source Code


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

import java.math.BigInteger;
import java.nio.ByteOrder;

public class Main {
    public final static int BITS_PER_BYTE = 8;

    public static BigInteger convertBytesToBigInteger(byte[] bytes, ByteOrder byteOrder, boolean isSigned) {

        if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
            bytes = toggleEndianess(bytes);
        }//from   w ww. j a v  a  2 s . co m

        BigInteger value = new BigInteger(bytes);

        int numberOfBytes = bytes.length;

        boolean valueIsLessThanZero = value.compareTo(BigInteger.ZERO) < 0;
        if (!isSigned && valueIsLessThanZero) {
            // Note: UNSIGNED_VALUE - SIGNED_VALUE = 2^NUMBER_OF_BITS
            // So to find which signed BigInteger value is equivalent to
            // the unsigned BigInteger value we want we use the following:
            // UNSIGNED_VALUE = SIGNED_VALUE + 2^NUMBER_OF_BITS
            BigInteger unsignedEquivalent = value.add(BigInteger.valueOf(2).pow(BITS_PER_BYTE * numberOfBytes));
            value = unsignedEquivalent;
        }
        return value;
    }

    private static byte[] toggleEndianess(byte[] bytes) {
        byte[] toggledBytes = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            toggledBytes[i] = bytes[bytes.length - i - 1];
        }
        return toggledBytes;
    }
}

Related

  1. byteArrayToNumber(byte[] data, int index, int length, ByteOrder byteOrder)
  2. complementingOrder(ByteOrder order)
  3. createWord(final ByteOrder aByteOrder, final int aMSB, final int aLSB)
  4. decode(final ByteOrder aExpectedByteOrder, final byte... aBytes)
  5. get24BitInt(byte b1, byte b2, byte b3, ByteOrder order)
  6. getByteOrder(final String value)