Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

In this page you can find the example usage for java.nio ByteBuffer order.

Prototype

Endianness order

To view the source code for java.nio ByteBuffer order.

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

From source file:org.mcisb.util.math.MathUtils.java

/**
 * // w  w w. j av a2 s  .  c  om
 * @param values
 * @param bigEndian
 * @return String
 */
public static byte[] getBytes(final double[] values, final boolean bigEndian) {
    final byte[] byteArray = new byte[values.length * DOUBLE_LENGTH];
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    buffer = buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < values.length; i++) {
        buffer.putDouble(values[i]);
    }

    return buffer.array();
}

From source file:org.mcisb.util.math.MathUtils.java

/**
 * //from  w  w w  .  j av a2  s .  c om
 * 
 * @param values
 * @param bigEndian
 * @return String
 */
public static String encode(final float[] values, final boolean bigEndian) {
    final byte[] byteArray = new byte[values.length * FLOAT_LENGTH];
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    buffer = buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < values.length; i++) {
        buffer.putFloat(values[i]);
    }

    // make the base64 strings from the bytes
    return Base64.encode(buffer.array());
}

From source file:org.broadinstitute.gatk.utils.io.IOUtils.java

/**
 * Determines the uncompressed size of a GZIP file. Uses the GZIP ISIZE field in the last
 * 4 bytes of the file to get this information.
 *
 * @param gzipFile GZIP-format file whose uncompressed size to determine
 * @return The uncompressed size (in bytes) of the GZIP file
 *//*from w  w  w  .  j av a  2s .  c o m*/
public static int getGZIPFileUncompressedSize(File gzipFile) {
    if (gzipFile == null) {
        throw new ReviewedGATKException("GZIP file to examine was null");
    }

    try {
        // The GZIP ISIZE field holds the uncompressed size of the compressed data.
        // It occupies the last 4 bytes of any GZIP file:
        RandomAccessFile in = new RandomAccessFile(gzipFile, "r");
        in.seek(gzipFile.length() - 4);
        byte[] sizeBytes = new byte[4];
        in.read(sizeBytes, 0, 4);

        ByteBuffer byteBuf = ByteBuffer.wrap(sizeBytes);
        byteBuf.order(ByteOrder.LITTLE_ENDIAN); // The GZIP spec mandates little-endian byte order
        int uncompressedSize = byteBuf.getInt();

        // If the size read in is negative, we've overflowed our signed integer:
        if (uncompressedSize < 0) {
            throw new UserException.CouldNotReadInputFile(String.format(
                    "Cannot accurately determine the uncompressed size of file %s "
                            + "because it's either larger than %d bytes or the GZIP ISIZE field is corrupt",
                    gzipFile.getAbsolutePath(), Integer.MAX_VALUE));
        }

        return uncompressedSize;
    } catch (IOException e) {
        throw new UserException.CouldNotReadInputFile(gzipFile, e);
    }
}

From source file:org.broadinstitute.sting.utils.io.IOUtils.java

/**
 * Determines the uncompressed size of a GZIP file. Uses the GZIP ISIZE field in the last
 * 4 bytes of the file to get this information.
 *
 * @param gzipFile GZIP-format file whose uncompressed size to determine
 * @return The uncompressed size (in bytes) of the GZIP file
 *//* www.  j a va 2  s  . com*/
public static int getGZIPFileUncompressedSize(File gzipFile) {
    if (gzipFile == null) {
        throw new ReviewedStingException("GZIP file to examine was null");
    }

    try {
        // The GZIP ISIZE field holds the uncompressed size of the compressed data.
        // It occupies the last 4 bytes of any GZIP file:
        RandomAccessFile in = new RandomAccessFile(gzipFile, "r");
        in.seek(gzipFile.length() - 4);
        byte[] sizeBytes = new byte[4];
        in.read(sizeBytes, 0, 4);

        ByteBuffer byteBuf = ByteBuffer.wrap(sizeBytes);
        byteBuf.order(ByteOrder.LITTLE_ENDIAN); // The GZIP spec mandates little-endian byte order
        int uncompressedSize = byteBuf.getInt();

        // If the size read in is negative, we've overflowed our signed integer:
        if (uncompressedSize < 0) {
            throw new UserException.CouldNotReadInputFile(String.format(
                    "Cannot accurately determine the uncompressed size of file %s "
                            + "because it's either larger than %d bytes or the GZIP ISIZE field is corrupt",
                    gzipFile.getAbsolutePath(), Integer.MAX_VALUE));
        }

        return uncompressedSize;
    } catch (IOException e) {
        throw new UserException.CouldNotReadInputFile(gzipFile, e);
    }
}

From source file:org.mcisb.util.math.MathUtils.java

/**
 * //from w  w w  . j  a v a2  s  .c  om
 * @param encoded
 * @param bigEndian
 * @param doublePrecision
 * @return double[]
 */
public static double[] decode(final byte[] encoded, final boolean bigEndian, final boolean doublePrecision) {
    final byte[] bytes = Base64.decode(encoded);
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    byteBuffer = byteBuffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);

    final int limit = byteBuffer.limit();
    double[] decoded = new double[((doublePrecision) ? limit / DOUBLE_LENGTH : limit / FLOAT_LENGTH)];
    int i = 0;

    while (byteBuffer.hasRemaining()) {
        if (doublePrecision) {
            decoded[i++] = byteBuffer.getDouble();
        } else {
            decoded[i++] = byteBuffer.getFloat();
        }
    }

    return decoded;
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Extract all ZipEntries from the ZIP central directory.
 *
 * @param buf/*w w w.j  a  va  2  s  .co m*/
 *     The byte buffer containing the ZIP central directory.
 *
 * @return A list with all ZipEntries.
 */
private static ArrayList<ExtendedZipEntry> parseHeaders(ByteBuffer buf) {
    ArrayList<ExtendedZipEntry> zeList = new ArrayList<ExtendedZipEntry>();

    buf.order(ByteOrder.LITTLE_ENDIAN);

    int offset = 0;

    while (offset < buf.limit() - ZipConstants.CENHDR) {
        short fileNameLen = buf.getShort(offset + ZipConstants.CENNAM);
        short extraFieldLen = buf.getShort(offset + ZipConstants.CENEXT);
        short fileCommentLen = buf.getShort(offset + ZipConstants.CENCOM);

        String fileName = new String(buf.array(), offset + ZipConstants.CENHDR, fileNameLen);

        ExtendedZipEntry zeGermans = new ExtendedZipEntry(fileName);

        zeGermans.setMethod(buf.getShort(offset + ZipConstants.CENHOW));

        CRC32 crc = new CRC32();
        crc.update(buf.getInt(offset + ZipConstants.CENCRC));
        zeGermans.setCrc(crc.getValue());

        zeGermans.setCompressedSize(buf.getInt(offset + ZipConstants.CENSIZ));
        zeGermans.setSize(buf.getInt(offset + ZipConstants.CENLEN));
        zeGermans.setInternalAttr(buf.getShort(offset + ZipConstants.CENATT));
        zeGermans.setExternalAttr(buf.getShort(offset + ZipConstants.CENATX));
        zeGermans.setOffset((long) buf.getInt(offset + ZipConstants.CENOFF));

        zeGermans.setExtraLength(extraFieldLen);

        zeList.add(zeGermans);
        offset += ZipConstants.CENHDR + fileNameLen + extraFieldLen + fileCommentLen;
    }

    return zeList;
}

From source file:org.openhab.io.transport.modbus.ModbusBitUtilities.java

/**
 * Read data from registers and convert the result to DecimalType
 * Interpretation of <tt>index</tt> goes as follows depending on type
 *
 * BIT://from w w w.  j  a v a 2s .  c o m
 * - a single bit is read from the registers
 * - indices between 0...15 (inclusive) represent bits of the first register
 * - indices between 16...31 (inclusive) represent bits of the second register, etc.
 * - index 0 refers to the least significant bit of the first register
 * - index 1 refers to the second least significant bit of the first register, etc.
 * INT8:
 * - a byte (8 bits) from the registers is interpreted as signed integer
 * - index 0 refers to low byte of the first register, 1 high byte of first register
 * - index 2 refers to low byte of the second register, 3 high byte of second register, etc.
 * - it is assumed that each high and low byte is encoded in most significant bit first order
 * UINT8:
 * - same as INT8 except value is interpreted as unsigned integer
 * INT16:
 * - register with index (counting from zero) is interpreted as 16 bit signed integer.
 * - it is assumed that each register is encoded in most significant bit first order
 * UINT16:
 * - same as INT16 except value is interpreted as unsigned integer
 * INT32:
 * - registers (index) and (index + 1) are interpreted as signed 32bit integer.
 * - it assumed that the first register contains the most significant 16 bits
 * - it is assumed that each register is encoded in most significant bit first order
 * INT32_SWAP:
 * - Same as INT32 but registers swapped
 * UINT32:
 * - same as INT32 except value is interpreted as unsigned integer
 * UINT32_SWAP:
 * - same as INT32_SWAP except value is interpreted as unsigned integer
 * FLOAT32:
 * - registers (index) and (index + 1) are interpreted as signed 32bit floating point number.
 * - it assumed that the first register contains the most significant 16 bits
 * - it is assumed that each register is encoded in most significant bit first order
 * - floating point NaN and infinity will return as empty optional
 * FLOAT32_SWAP:
 * - Same as FLOAT32 but registers swapped
 * INT64:
 * - registers (index), (index + 1), (index + 2), (index + 3) are interpreted as signed 64bit integer.
 * - it assumed that the first register contains the most significant 16 bits
 * - it is assumed that each register is encoded in most significant bit first order
 * INT64_SWAP:
 * - same as INT64 but registers swapped, that is, registers (index + 3), (index + 2), (index + 1), (index + 1) are
 * interpreted as signed 64bit integer
 * UINT64:
 * - same as INT64 except value is interpreted as unsigned integer
 * UINT64_SWAP:
 * - same as INT64_SWAP except value is interpreted as unsigned integer
 *
 * @param registers list of registers, each register represent 16bit of data
 * @param index zero based item index. Interpretation of this depends on type, see examples above.
 *            With type larger or equal to 16 bits, the index tells the register index to start reading
 *            from.
 *            With type less than 16 bits, the index tells the N'th item to read from the registers.
 * @param type item type, e.g. unsigned 16bit integer (<tt>ModbusBindingProvider.ValueType.UINT16</tt>)
 * @return number representation queried value, <tt>DecimalType</tt>. Empty optional is returned
 *         with NaN and infinity floating point values
 * @throws NotImplementedException in cases where implementation is lacking for the type. This can be considered a
 *             bug
 * @throws IllegalArgumentException when <tt>index</tt> is out of bounds of registers
 *
 */
public static Optional<DecimalType> extractStateFromRegisters(ModbusRegisterArray registers, int index,
        ModbusConstants.ValueType type) {
    int endBitIndex = (type.getBits() >= 16 ? 16 * index : type.getBits() * index) + type.getBits() - 1;
    // each register has 16 bits
    int lastValidIndex = registers.size() * 16 - 1;
    if (endBitIndex > lastValidIndex || index < 0) {
        throw new IllegalArgumentException(
                String.format("Index=%d with type=%s is out-of-bounds given registers of size %d", index, type,
                        registers.size()));
    }
    switch (type) {
    case BIT:
        return Optional
                .of(new DecimalType((registers.getRegister(index / 16).toUnsignedShort() >> (index % 16)) & 1));
    case INT8:
        return Optional.of(new DecimalType(registers.getRegister(index / 2).getBytes()[1 - (index % 2)]));
    case UINT8:
        return Optional.of(new DecimalType(
                (registers.getRegister(index / 2).toUnsignedShort() >> (8 * (index % 2))) & 0xff));
    case INT16: {
        ByteBuffer buff = ByteBuffer.allocate(2);
        buff.put(registers.getRegister(index).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getShort(0)));
    }
    case UINT16:
        return Optional.of(new DecimalType(registers.getRegister(index).toUnsignedShort()));
    case INT32: {
        ByteBuffer buff = ByteBuffer.allocate(4);
        buff.put(registers.getRegister(index).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0)));
    }
    case UINT32: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.position(4);
        buff.put(registers.getRegister(index).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0)));
    }
    case FLOAT32: {
        ByteBuffer buff = ByteBuffer.allocate(4);
        buff.put(registers.getRegister(index).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        try {
            return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0)));
        } catch (NumberFormatException e) {
            // floating point NaN or infinity encountered
            return Optional.empty();
        }
    }
    case INT64: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.put(registers.getRegister(index).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index + 2).getBytes());
        buff.put(registers.getRegister(index + 3).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0)));
    }
    case UINT64: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.put(registers.getRegister(index).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index + 2).getBytes());
        buff.put(registers.getRegister(index + 3).getBytes());
        return Optional.of(
                new DecimalType(new BigDecimal(new BigInteger(1, buff.order(ByteOrder.BIG_ENDIAN).array()))));
    }
    case INT32_SWAP: {
        ByteBuffer buff = ByteBuffer.allocate(4);
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0)));
    }
    case UINT32_SWAP: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.position(4);
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0)));
    }
    case FLOAT32_SWAP: {
        ByteBuffer buff = ByteBuffer.allocate(4);
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index).getBytes());
        try {
            return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0)));
        } catch (NumberFormatException e) {
            // floating point NaN or infinity encountered
            return Optional.empty();
        }
    }
    case INT64_SWAP: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.put(registers.getRegister(index + 3).getBytes());
        buff.put(registers.getRegister(index + 2).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index).getBytes());
        return Optional.of(new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0)));
    }
    case UINT64_SWAP: {
        ByteBuffer buff = ByteBuffer.allocate(8);
        buff.put(registers.getRegister(index + 3).getBytes());
        buff.put(registers.getRegister(index + 2).getBytes());
        buff.put(registers.getRegister(index + 1).getBytes());
        buff.put(registers.getRegister(index).getBytes());
        return Optional.of(
                new DecimalType(new BigDecimal(new BigInteger(1, buff.order(ByteOrder.BIG_ENDIAN).array()))));
    }
    default:
        throw new IllegalArgumentException(type.getConfigValue());
    }
}

From source file:io.ecarf.core.utils.Utils.java

/**
 * Get the likely uncompressed size of a Gziped file
 * @param filename// w  ww. j av  a 2s  . co  m
 * @return
 * @throws IOException 
 * @see http://stackoverflow.com/questions/27825927/get-gzipped-file-attributes-like-gzip-l-basically-compression-ratio
 * @throws FileNotFoundException 
 */
public static long getUncompressedFileSize(String filename) throws FileNotFoundException, IOException {

    File f = new File(filename);
    try (RandomAccessFile ra = new RandomAccessFile(f, "r"); FileChannel channel = ra.getChannel()) {

        MappedByteBuffer fileBuffer = channel.map(MapMode.READ_ONLY, f.length() - 4, 4);
        fileBuffer.load();

        ByteBuffer buf = ByteBuffer.allocate(4);
        buf.order(ByteOrder.LITTLE_ENDIAN);

        buf.put(fileBuffer);
        buf.flip();
        //will print the uncompressed size
        //getInt() reads the 4 bytes as a int
        // if the file is between 2GB and 4GB
        // then this will return a negative value
        //and you'll have to do your own converting to an unsigned int
        int size = buf.getInt();

        if (size < 0) {
            return FileUtils.ONE_GB + size;
        } else {
            return size;
        }
    }
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

public static ByteBuffer bytebuffer(Long val) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(val);
    return (ByteBuffer) buf.rewind();
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

/**
 * @param val/*from  ww  w. java  2s.  c  o m*/
 * @return
 */
public static byte[] bytes(Long val) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(val);
    return buf.array();
}