Example usage for java.nio ByteOrder LITTLE_ENDIAN

List of usage examples for java.nio ByteOrder LITTLE_ENDIAN

Introduction

In this page you can find the example usage for java.nio ByteOrder LITTLE_ENDIAN.

Prototype

ByteOrder LITTLE_ENDIAN

To view the source code for java.nio ByteOrder LITTLE_ENDIAN.

Click Source Link

Document

This constant represents little endian.

Usage

From source file:srebrinb.compress.sevenzip.SevenZFile.java

private ByteBuffer readEncodedHeader(final ByteBuffer header, final Archive archive, final byte[] password)
        throws IOException {
    readStreamsInfo(header, archive);/*www.  j  a v  a  2  s.  c om*/

    // FIXME: merge with buildDecodingStream()/buildDecoderStack() at some stage?
    final Folder folder = archive.folders[0];
    final int firstPackStreamIndex = 0;
    final long folderOffset = SIGNATURE_HEADER_SIZE + archive.packPos + 0;

    channel.position(folderOffset);
    InputStream inputStreamStack = new BoundedSeekableByteChannelInputStream(channel,
            archive.packSizes[firstPackStreamIndex]);
    for (final Coder coder : folder.getOrderedCoders()) {
        if (coder.numInStreams != 1 || coder.numOutStreams != 1) {
            throw new IOException("Multi input/output stream coders are not yet supported");
        }
        inputStreamStack = Coders.addDecoder(fileName, inputStreamStack, //NOSONAR
                folder.getUnpackSizeForCoder(coder), coder, password);
    }
    if (folder.hasCrc) {
        inputStreamStack = new CRC32VerifyingInputStream(inputStreamStack, folder.getUnpackSize(), folder.crc);
    }
    final byte[] nextHeader = new byte[(int) folder.getUnpackSize()];
    try (DataInputStream nextHeaderInputStream = new DataInputStream(inputStreamStack)) {
        nextHeaderInputStream.readFully(nextHeader);
    }
    return ByteBuffer.wrap(nextHeader).order(ByteOrder.LITTLE_ENDIAN);
}

From source file:de.undercouch.bson4jackson.BsonParser.java

/**
 * Can be called when a new embedded document is found. Reads the
 * document's header and creates a new context on the stack.
 * @param array true if the document is an embedded array
 * @return the json token read/*  w  w w .ja  v  a 2 s. co m*/
 * @throws IOException if an I/O error occurs
 */
protected JsonToken handleNewDocument(boolean array) throws IOException {
    if (_in == null) {
        //this means Feature.HONOR_DOCUMENT_LENGTH is enabled, and we
        //haven't yet started reading. Read the first int to find out the
        //length of the document.
        byte[] buf = new byte[Integer.SIZE / Byte.SIZE];
        int len = 0;
        while (len < buf.length) {
            int l = _rawInputStream.read(buf, len, buf.length - len);
            if (l == -1) {
                throw new IOException("Not enough bytes for length of document");
            }
            len += l;
        }

        //wrap the input stream by a bounded stream, subtract buf.length from the
        //length because the size itself is included in the length
        int documentLength = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        InputStream in = new BoundedInputStream(_rawInputStream, documentLength - buf.length);

        //buffer if the raw input stream is not already buffered
        if (!(_rawInputStream instanceof BufferedInputStream)) {
            in = new StaticBufferedInputStream(in);
        }
        _counter = new CountingInputStream(in);
        _in = new LittleEndianInputStream(_counter);
    } else {
        //read document header (skip size, we're not interested)
        _in.readInt();
    }

    _currentContext = new Context(_currentContext, array);
    return (array ? JsonToken.START_ARRAY : JsonToken.START_OBJECT);
}

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

/**
 * Get a {@link java.net.HttpURLConnection} that has its {@link java.io.InputStream} pointing at
 * the file data of the given {@link guru.benson.pinch.ExtendedZipEntry}.
 *
 * @throws IOException/*from  w  ww .  j  a v a  2 s.com*/
 */
private HttpURLConnection getEntryInputStream(ExtendedZipEntry entry) throws IOException {
    HttpURLConnection conn;
    InputStream is;

    // Define the local header range
    long start = entry.getOffset();
    long end = start + ZipConstants.LOCHDR;

    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    byte[] dataBuffer = new byte[2048];
    int read, bytes = 0;

    is = conn.getInputStream();
    while ((read = is.read(dataBuffer)) != -1) {
        bytes += read;
    }
    close(is);
    disconnect(conn);
    if (bytes < ZipConstants.LOCHDR) {
        throw new IOException("Unable to fetch the local header");
    }

    ByteBuffer buffer = ByteBuffer.allocate(ZipConstants.LOCHDR);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(dataBuffer, 0, ZipConstants.LOCHDR);

    final int headerSignature = buffer.getInt(0);
    if (headerSignature != 0x04034b50) {
        disconnect(conn);
        throw new IOException("Local file header signature mismatch");
    }

    final int localCompressedSize = buffer.getInt(ZipConstants.LOCSIZ);
    final short localFileNameLength = buffer.getShort(ZipConstants.LOCNAM);
    final short localExtraLength = buffer.getShort(ZipConstants.LOCEXT);

    // Define the local file range
    start = entry.getOffset() + ZipConstants.LOCHDR + localFileNameLength + localExtraLength;
    end = start + localCompressedSize;

    // Open a new one with
    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        disconnect(conn);
        close(is);
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    return conn;
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public void setSampleRateManual(int frequency, int divider) throws UsbException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);

    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(frequency);//from   w w w .  j  a v  a2  s.com
    buffer.putInt(divider);

    write(Request.SET_SAMPLE_RATE, 0, 0, buffer);
}

From source file:nrec.basil.wimuconsole.SensorSettingsActivity.java

private void displayInsData(byte[] ins) {
    TextView t;//  ww  w . j  ava2  s  .  co m
    DecimalFormat form = new DecimalFormat("##0.00");
    ByteBuffer insbuffer = ByteBuffer.wrap(ins);
    insbuffer.order(ByteOrder.LITTLE_ENDIAN);
    // Display INS data
    t = (TextView) findViewById(R.id.statusreport);
    String status = null;
    byte stat = insbuffer.get(22);
    if (D)
        Log.d(TAG, "INS Status: " + stat);
    switch (stat) {
    case 0:
        status = "Calibrating";
        break;
    case 1:
        status = "Aligning";
        break;
    case 2:
        status = "Navigating";
        break;
    case 3:
        status = "Invalid Data";
        break;
    case 4:
        status = "Stopped";
        break;
    }
    t.setText(status);

    t = (TextView) findViewById(R.id.solutionreport);
    String solution = null;
    solution = String.format("%8s", Integer.toBinaryString(insbuffer.get(23) & 0xFF)).replace(' ', '0');
    t.setText(solution);

    t = (TextView) findViewById(R.id.px);
    mCurrentLatitude = insbuffer.getDouble(25);
    t.setText(form.format(insbuffer.getDouble(25)));
    t = (TextView) findViewById(R.id.py);
    mCurrentLongitude = insbuffer.getDouble(33);
    t.setText(form.format(insbuffer.getDouble(33)));
    t = (TextView) findViewById(R.id.pz);
    t.setText(form.format(insbuffer.getDouble(41)));
    t = (TextView) findViewById(R.id.vx);
    t.setText(form.format(insbuffer.getDouble(49)));
    t = (TextView) findViewById(R.id.vy);
    t.setText(form.format(insbuffer.getDouble(57)));
    t = (TextView) findViewById(R.id.vz);
    t.setText(form.format(insbuffer.getDouble(65)));
    t = (TextView) findViewById(R.id.ox);
    t.setText(form.format(insbuffer.getDouble(73) * R2D));
    t = (TextView) findViewById(R.id.oy);
    t.setText(form.format(insbuffer.getDouble(81) * R2D));
    t = (TextView) findViewById(R.id.oz);
    t.setText(form.format(insbuffer.getDouble(89) * R2D));
}

From source file:it.unimi.di.big.mg4j.index.DiskBasedIndex.java

/** Parses a {@link ByteOrder} value.
 * //from  w  w  w  .ja  v  a2  s .com
 * @param s a string (either <samp>BIG_ENDIAN</samp> or <samp>LITTLE_ENDIAN</samp>).
 * @return the corresponding byte order ({@link ByteOrder#BIG_ENDIAN} or {@link ByteOrder#LITTLE_ENDIAN}).
 */
public static ByteOrder byteOrder(final String s) {
    if (s.equals(ByteOrder.BIG_ENDIAN.toString()))
        return ByteOrder.BIG_ENDIAN;
    if (s.equals(ByteOrder.LITTLE_ENDIAN.toString()))
        return ByteOrder.LITTLE_ENDIAN;
    throw new IllegalArgumentException("Unknown byte order " + s);
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

private long readHeader() throws IOException {
    ByteBuffer tiffHeader = ByteBuffer.allocate(8);
    fileChannel_.read(tiffHeader, 0);/*from  w  w w  .  ja v  a  2 s .  c o  m*/
    char zeroOne = tiffHeader.getChar(0);
    if (zeroOne == 0x4949) {
        byteOrder_ = ByteOrder.LITTLE_ENDIAN;
    } else if (zeroOne == 0x4d4d) {
        byteOrder_ = ByteOrder.BIG_ENDIAN;
    } else {
        throw new IOException("Error reading Tiff header");
    }
    tiffHeader.order(byteOrder_);
    short twoThree = tiffHeader.getShort(2);
    if (twoThree != 42) {
        throw new IOException("Tiff identifier code incorrect");
    }
    return unsignInt(tiffHeader.getInt(4));
}

From source file:org.mycontroller.standalone.mysensors.MySensorsMessageEngine.java

private void procressFirmwareRequest(MySensorsRawMessage mySensorsRawMessage) {
    FirmwareRequest firmwareRequest = new FirmwareRequest();
    try {//from w w  w  . ja  v a  2  s  .c  om
        firmwareRequest
                .setByteBuffer(ByteBuffer.wrap(Hex.decodeHex(mySensorsRawMessage.getPayload().toCharArray()))
                        .order(ByteOrder.LITTLE_ENDIAN), 0);
        _logger.debug("Firmware Request:[Type:{},Version:{},Block:{}]", firmwareRequest.getType(),
                firmwareRequest.getVersion(), firmwareRequest.getBlock());

        boolean requestFirmwareReload = false;
        if (firmware == null) {
            requestFirmwareReload = true;
        } else if (firmware != null) {
            if (firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
                requestFirmwareReload = true;
            } else if (firmwareRequest.getType() == firmware.getType().getId()
                    && firmwareRequest.getVersion() == firmware.getVersion().getId()) {
                //Nothing to do just continue
            } else {
                requestFirmwareReload = true;
            }
        } else {
            requestFirmwareReload = true;
        }

        if (requestFirmwareReload) {
            firmware = DaoUtils.getFirmwareDao().get(firmwareRequest.getType(), firmwareRequest.getVersion());
            _logger.debug("Firmware reloaded...");
        }

        if (firmware == null) {
            _logger.debug("selected firmware type/version not available");
            return;
        }

        FirmwareResponse firmwareResponse = new FirmwareResponse();
        firmwareResponse.setByteBufferPosition(0);
        firmwareResponse.setBlock(firmwareRequest.getBlock());
        firmwareResponse.setVersion(firmwareRequest.getVersion());
        firmwareResponse.setType(firmwareRequest.getType());
        StringBuilder builder = new StringBuilder();
        int fromIndex = firmwareRequest.getBlock() * FirmwareUtils.FIRMWARE_BLOCK_SIZE;
        for (int index = fromIndex; index < fromIndex + FirmwareUtils.FIRMWARE_BLOCK_SIZE; index++) {
            builder.append(String.format("%02X", firmware.getData().get(index)));
        }
        if (firmwareRequest.getBlock() == 0) {
            firmware = null;
            _logger.debug("Firmware unloaded...");
        }

        // Print firmware status in sensor logs
        if (firmwareRequest.getBlock() % FIRMWARE_PRINT_LOG == 0
                || firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
            //ResourcesLogs message data
            if (ResourcesLogsUtils.isLevel(LOG_LEVEL.INFO)) {
                this.setSensorOtherData(LOG_LEVEL.INFO, mySensorsRawMessage,
                        MESSAGE_TYPE_STREAM.ST_FIRMWARE_REQUEST.getText(),
                        "Block No: " + firmwareRequest.getBlock());
            }
        }

        mySensorsRawMessage.setTxMessage(true);
        mySensorsRawMessage.setSubType(MESSAGE_TYPE_STREAM.ST_FIRMWARE_RESPONSE.ordinal());
        mySensorsRawMessage
                .setPayload(Hex.encodeHexString(firmwareResponse.getByteBuffer().array()) + builder.toString());
        ObjectFactory.getRawMessageQueue().putMessage(mySensorsRawMessage.getRawMessage());
        _logger.debug("FirmwareRespone:[Type:{},Version:{},Block:{}]", firmwareResponse.getType(),
                firmwareResponse.getVersion(), firmwareResponse.getBlock());

        // Print firmware status in sensor logs
        if (firmwareRequest.getBlock() % FIRMWARE_PRINT_LOG == 0
                || firmwareRequest.getBlock() == (firmware.getBlocks() - 1)) {
            //ResourcesLogs message data
            if (ResourcesLogsUtils.isLevel(LOG_LEVEL.INFO)) {
                this.setSensorOtherData(LOG_LEVEL.INFO, mySensorsRawMessage,
                        MESSAGE_TYPE_STREAM.ST_FIRMWARE_RESPONSE.getText(),
                        "Block No:" + firmwareRequest.getBlock());
            }

        }

    } catch (DecoderException ex) {
        _logger.error("Exception, ", ex);
    }
}

From source file:au.org.ala.layers.intersect.Grid.java

public float[] getGrid() {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (grid_data != null) {
        return grid_data;
    }/*w w w  . j a v  a2  s.  c  o m*/

    Grid loadedAlready = getLoadedGrid(filename);
    if (loadedAlready != null && loadedAlready.grid_data != null) {
        return loadedAlready.grid_data;
    }

    int length = nrows * ncols;

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[(int) Math.min(afile.length(), maxArrayLength)];

        int i = 0;
        int max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[i] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:org.mycontroller.standalone.mysensors.ProcessRawMessage.java

private void processFirmwareConfigRequest(RawMessage rawMessage) {
    FirmwareConfigRequest firmwareConfigRequest = new FirmwareConfigRequest();
    try {//from ww w.  ja va2s  .com
        firmwareConfigRequest.setByteBuffer(ByteBuffer
                .wrap(Hex.decodeHex(rawMessage.getPayload().toCharArray())).order(ByteOrder.LITTLE_ENDIAN), 0);
        boolean bootLoaderCommand = false;
        Firmware firmware = null;

        //Check firmware is configured for this particular node
        Node node = DaoUtils.getNodeDao().get(rawMessage.getNodeId());
        if (node != null && node.getEraseEEPROM() != null && node.getEraseEEPROM()) {
            bootLoaderCommand = true;
            _logger.debug("Erase EEPROM has been set...");
        } else if (node != null && node.getFirmware() != null) {
            firmware = DaoUtils.getFirmwareDao().get(node.getFirmware().getId());
            _logger.debug("Firmware selected based on node configuration...");
        } else if (firmwareConfigRequest.getType() == 65535 && firmwareConfigRequest.getVersion() == 65535) {
            Settings defailtFirmware = DaoUtils.getSettingsDao().get(Settings.DEFAULT_FIRMWARE);
            if (defailtFirmware != null && defailtFirmware.getValue() != null) {
                firmware = DaoUtils.getFirmwareDao().get(Integer.valueOf(defailtFirmware.getValue()));
            } else {
                _logger.warn("There is no default firmware set!");
            }
        } else {
            firmware = DaoUtils.getFirmwareDao().get(firmwareConfigRequest.getType(),
                    firmwareConfigRequest.getVersion());
        }

        FirmwareConfigResponse firmwareConfigResponse = new FirmwareConfigResponse();
        firmwareConfigResponse.setByteBufferPosition(0);

        if (bootLoaderCommand) {//If it is bootloader command
            if (node.getEraseEEPROM() != null && node.getEraseEEPROM()) {
                firmwareConfigResponse.loadEraseEepromCommand();
                node.setEraseEEPROM(false); //Remove erase EEPROM flag and update in to database
                DaoUtils.getNodeDao().update(node);
            } else {
                _logger.warn("Selected booloader command is not available, FirmwareConfigRequest:[{}]",
                        firmwareConfigRequest);
                return;
            }
        } else if (firmware == null) {//Non bootloader command
            if (DaoUtils.getSettingsDao().get(Settings.ENABLE_NOT_AVAILABLE_TO_DEFAULT_FIRMWARE).getValue()
                    .equalsIgnoreCase("true")) {
                _logger.debug(
                        "If requested firmware is not available, redirect to default firmware is set, Checking the default firmware");
                Settings defailtFirmware = DaoUtils.getSettingsDao().get(Settings.DEFAULT_FIRMWARE);
                if (defailtFirmware != null && defailtFirmware.getValue() != null) {
                    firmware = DaoUtils.getFirmwareDao().get(Integer.valueOf(defailtFirmware.getValue()));
                    _logger.debug("Default firmware:[{}]", firmware.getFirmwareName());
                } else {
                    _logger.warn("There is no default firmware set!");
                }
            }
            //Selected, default: No firmware available for this request
            if (firmware == null) {
                _logger.warn("Selected Firmware is not available, FirmwareConfigRequest:[{}]",
                        firmwareConfigRequest);
                return;
            }
        }

        if (firmware != null) {
            firmwareConfigResponse.setType(firmware.getType().getId());
            firmwareConfigResponse.setVersion(firmware.getVersion().getId());
            firmwareConfigResponse.setBlocks(firmware.getBlocks());
            firmwareConfigResponse.setCrc(firmware.getCrc());
        }

        rawMessage.setTxMessage(true);
        rawMessage.setSubType(MESSAGE_TYPE_STREAM.ST_FIRMWARE_CONFIG_RESPONSE.ordinal());
        rawMessage
                .setPayload(Hex.encodeHexString(firmwareConfigResponse.getByteBuffer().array()).toUpperCase());
        ObjectFactory.getRawMessageQueue().putMessage(rawMessage);
        _logger.debug("FirmwareConfigRequest:[{}]", firmwareConfigRequest);
        _logger.debug("FirmwareConfigResponse:[{}]", firmwareConfigResponse);
    } catch (DecoderException ex) {
        _logger.error("Exception, ", ex);
    }
}