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:nl.salp.warcraft4j.casc.cdn.EncodingFileParser.java

private EncodingFileHeader parseHeader(DataReader reader)
        throws DataReadingException, DataParsingException, CascParsingException {
    String magicString = reader.readNext(DataTypeFactory.getFixedLengthString(2, StandardCharsets.US_ASCII));
    if (!MAGIC_STRING.equals(magicString)) {
        throw new CascParsingException(
                format("Encoding file starts with magic string %s instead of %s", magicString, MAGIC_STRING));
    }/* w  w  w  .  j a v  a  2  s. c  o  m*/
    byte[] unknown1 = reader.readNext(DataTypeFactory.getByteArray(3));
    int unknown2 = reader.readNext(DataTypeFactory.getUnsignedShort(), ByteOrder.LITTLE_ENDIAN);
    int unknown3 = reader.readNext(DataTypeFactory.getUnsignedShort(), ByteOrder.LITTLE_ENDIAN);
    long segmentCount = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.BIG_ENDIAN);
    long unknown4 = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.BIG_ENDIAN);
    byte unknown5 = reader.readNext(DataTypeFactory.getByte());
    long segmentOffset = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.BIG_ENDIAN);
    return new EncodingFileHeader(magicString, unknown1, unknown2, unknown3, segmentCount, unknown4, unknown5,
            segmentOffset);
}

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

private Archive readHeaders(final byte[] password) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(12 /* signature + 2 bytes version + 4 bytes CRC */)
            .order(ByteOrder.LITTLE_ENDIAN);
    readFully(buf);//from   w w w.  j a va  2  s  .c  o m
    final byte[] signature = new byte[6];
    buf.get(signature);
    if (!Arrays.equals(signature, sevenZSignature)) {
        throw new IOException("Bad 7z signature");
    }
    // 7zFormat.txt has it wrong - it's first major then minor
    final byte archiveVersionMajor = buf.get();
    final byte archiveVersionMinor = buf.get();
    if (archiveVersionMajor != 0) {
        throw new IOException(
                String.format("Unsupported 7z version (%d,%d)", archiveVersionMajor, archiveVersionMinor));
    }

    final long startHeaderCrc = 0xffffFFFFL & buf.getInt();
    final StartHeader startHeader = readStartHeader(startHeaderCrc);

    final int nextHeaderSizeInt = (int) startHeader.nextHeaderSize;
    if (nextHeaderSizeInt != startHeader.nextHeaderSize) {
        throw new IOException("cannot handle nextHeaderSize " + startHeader.nextHeaderSize);
    }
    channel.position(SIGNATURE_HEADER_SIZE + startHeader.nextHeaderOffset);
    buf = ByteBuffer.allocate(nextHeaderSizeInt).order(ByteOrder.LITTLE_ENDIAN);
    readFully(buf);
    final CRC32 crc = new CRC32();
    crc.update(buf.array());
    if (startHeader.nextHeaderCrc != crc.getValue()) {
        throw new IOException("NextHeader CRC mismatch");
    }

    Archive archive = new Archive();
    int nid = getUnsignedByte(buf);
    if (nid == NID.kEncodedHeader) {
        buf = readEncodedHeader(buf, archive, password);
        // Archive gets rebuilt with the new header
        archive = new Archive();
        nid = getUnsignedByte(buf);
    }
    if (nid == NID.kHeader) {
        readHeader(buf, archive);
    } else {
        throw new IOException("Broken or unsupported archive: no Header");
    }
    return archive;
}

From source file:adapter.davis.DavisSensor.java

/**
 * Expecting ACK message.//from  ww w. j  a v a2 s  .c o m
 * @throws CommunicationException
 * @throws InterruptedException
 */
private void expectACK() throws CommunicationException, InterruptedException {
    logger.info("Expecting ACK");
    byte ans[] = this.expect(1);

    ByteBuffer wrapped = ByteBuffer.wrap(ans, 0, ans.length);
    wrapped.order(ByteOrder.LITTLE_ENDIAN);

    if (wrapped.get() != DavisReturnCodes.ACK)
        throw new CommunicationException("Didn't receive ACK");

    logger.info("Received ACK successful.");
}

From source file:com.tesora.dve.db.mysql.DBTypeBasedUtilsTest.java

@Test
public void sqlReadWriteTest() throws Exception {
    ByteBuf cb = Unpooled.buffer(100).order(ByteOrder.LITTLE_ENDIAN);

    for (Pair<Integer, Object> expValue : expValuesSQL) {
        cb.clear();/*from   w w w.jav  a  2  s.c om*/
        DataTypeValueFunc dtvf = DBTypeBasedUtils.getSQLTypeFunc(expValue.getFirst());
        dtvf.writeObject(cb, expValue.getSecond());
        assertEqualData(expValue.getSecond(), dtvf.readObject(cb));
    }
}

From source file:io.github.msdk.io.mzdata.MzDataSaxHandler.java

/**
 * {@inheritDoc}/*w  w  w.  j a  va 2  s.c  o  m*/
 *
 * endElement()
 */
@SuppressWarnings("null")
public void endElement(String namespaceURI, String sName, String qName) throws SAXException {

    if (canceled)
        throw new SAXException("Parsing Cancelled");

    // <spectrumInstrument>
    if (qName.equalsIgnoreCase("spectrumInstrument")) {
        spectrumInstrumentFlag = false;
    }

    // <precursor>
    if (qName.equalsIgnoreCase("precursor")) {
        precursorFlag = false;
    }

    // <spectrum>
    if (qName.equalsIgnoreCase("spectrum")) {

        spectrumInstrumentFlag = false;

        // Auto-detect whether this scan is centroided
        MsSpectrumType spectrumType = SpectrumTypeDetectionAlgorithm.detectSpectrumType(mzBuffer,
                intensityBuffer, peaksCount);

        // Create a new scan
        MsFunction msFunction = MSDKObjectBuilder.getMsFunction(msLevel);

        MsScan newScan = MSDKObjectBuilder.getMsScan(dataStore, scanNumber, msFunction);

        newScan.setDataPoints(mzBuffer, intensityBuffer, peaksCount);
        newScan.setSpectrumType(spectrumType);
        newScan.setPolarity(polarity);

        if (retentionTime != null) {
            ChromatographyInfo chromInfo = MSDKObjectBuilder.getChromatographyInfo1D(SeparationType.UNKNOWN,
                    retentionTime);
            newScan.setChromatographyInfo(chromInfo);
        }

        if (precursorMz != null) {
            IsolationInfo isolation = MSDKObjectBuilder.getIsolationInfo(Range.singleton(precursorMz), null,
                    precursorMz, precursorCharge, null);
            newScan.getIsolations().add(isolation);
        }

        // Add the scan to the file
        newRawFile.addScan(newScan);
        parsedScans++;

    }

    // <mzArrayBinary>
    if (qName.equalsIgnoreCase("mzArrayBinary")) {

        mzArrayBinaryFlag = false;

        // Allocate space for the whole array
        if (mzBuffer.length < peaksCount)
            mzBuffer = new double[peaksCount * 2];

        byte[] peakBytes = Base64.decodeBase64(charBuffer.toString().getBytes());

        ByteBuffer currentMzBytes = ByteBuffer.wrap(peakBytes);

        if (endian.equals("big")) {
            currentMzBytes = currentMzBytes.order(ByteOrder.BIG_ENDIAN);
        } else {
            currentMzBytes = currentMzBytes.order(ByteOrder.LITTLE_ENDIAN);
        }

        for (int i = 0; i < peaksCount; i++) {
            if (precision == null || precision.equals("32"))
                mzBuffer[i] = (double) currentMzBytes.getFloat();
            else
                mzBuffer[i] = currentMzBytes.getDouble();
        }

    }

    // <intenArrayBinary>
    if (qName.equalsIgnoreCase("intenArrayBinary")) {

        intenArrayBinaryFlag = false;

        // Allocate space for the whole array
        if (intensityBuffer.length < peaksCount)
            intensityBuffer = new float[peaksCount * 2];

        byte[] peakBytes = Base64.decodeBase64(charBuffer.toString().getBytes());

        ByteBuffer currentIntensityBytes = ByteBuffer.wrap(peakBytes);

        if (endian.equals("big")) {
            currentIntensityBytes = currentIntensityBytes.order(ByteOrder.BIG_ENDIAN);
        } else {
            currentIntensityBytes = currentIntensityBytes.order(ByteOrder.LITTLE_ENDIAN);
        }

        for (int i = 0; i < peaksCount; i++) {
            if (precision == null || precision.equals("32"))
                intensityBuffer[i] = currentIntensityBytes.getFloat();
            else
                intensityBuffer[i] = (float) currentIntensityBytes.getDouble();
        }
    }
}

From source file:nl.salp.warcraft4j.casc.cdn.local.LocalIndexFileParser.java

/**
 * Read and parse an {@link IndexEntry}.
 *
 * @param reader The reader to read the entry data from.
 *
 * @return The parsed entry.//from w  ww .ja va 2 s. co m
 *
 * @throws DataReadingException When reading the entry data failed.
 * @throws DataParsingException When parsing the entry data failed.
 */
private IndexEntry parseEntry(DataReader reader) throws DataReadingException, DataParsingException {
    byte[] fileKey = reader.readNext(DataTypeFactory.getByteArray(9));
    short indexInfoHigh = reader.readNext(DataTypeFactory.getUnsignedByte());
    long indexInfoLow = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.BIG_ENDIAN);
    long fileSize = reader.readNext(DataTypeFactory.getUnsignedInteger(), ByteOrder.LITTLE_ENDIAN);
    IndexEntry entry = new LocalIndexEntry(new FileKey(fileKey), indexInfoHigh, indexInfoLow, fileSize);
    return entry;
}

From source file:org.apache.spark.sql.execution.vectorized.OffHeapColumnVector.java

@Override
public void putFloats(int rowId, int count, byte[] src, int srcIndex) {
    if (!bigEndianPlatform) {
        Platform.copyMemory(src, Platform.BYTE_ARRAY_OFFSET + srcIndex, null, data + rowId * 4, count * 4);
    } else {/*from ww  w  .j  a  v  a2s.c  om*/
        ByteBuffer bb = ByteBuffer.wrap(src).order(ByteOrder.LITTLE_ENDIAN);
        long offset = data + 4 * rowId;
        for (int i = 0; i < count; ++i, offset += 4) {
            Platform.putFloat(null, offset, bb.getFloat(srcIndex + (4 * i)));
        }
    }
}

From source file:com.github.woz_dialog.ros_woz_dialog_project.TTSHTTPClient.java

private static byte[] addWavHeader(byte[] bytes) throws IOException {

    ByteBuffer bufferWithHeader = ByteBuffer.allocate(bytes.length + 44);
    bufferWithHeader.order(ByteOrder.LITTLE_ENDIAN);
    bufferWithHeader.put("RIFF".getBytes());
    bufferWithHeader.putInt(bytes.length + 36);
    bufferWithHeader.put("WAVE".getBytes());
    bufferWithHeader.put("fmt ".getBytes());
    bufferWithHeader.putInt(16);//from  ww  w . ja v a2 s .  c  om
    bufferWithHeader.putShort((short) 1);
    bufferWithHeader.putShort((short) 1);
    bufferWithHeader.putInt(16000);
    bufferWithHeader.putInt(32000);
    bufferWithHeader.putShort((short) 2);
    bufferWithHeader.putShort((short) 16);
    bufferWithHeader.put("data".getBytes());
    bufferWithHeader.putInt(bytes.length);
    bufferWithHeader.put(bytes);
    return bufferWithHeader.array();
}

From source file:org.xenei.bloomgraph.bloom.sql.DBIO.java

/**
 * copy the blob to a byte buffer./*from w w w.j  a va 2 s  .com*/
 * 
 * @param blob
 *            The blob to read
 * @return A bytebuffer with the blob contents.
 * @throws IOException
 *             on copy error
 * @throws SQLException
 *             on db error
 */
public static ByteBuffer toByteBuffer(final Blob blob) throws IOException, SQLException {
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        IOUtils.copy(blob.getBinaryStream(), baos);
        return ByteBuffer.wrap(baos.toByteArray()).order(ByteOrder.LITTLE_ENDIAN);
    } finally {
        IOUtils.closeQuietly(baos);
    }
}

From source file:ffx.crystal.CCP4MapWriter.java

/**
 * write data to file, does not normalize
 *
 * @param data map data to write out/* www  .  j a  v  a2s .co m*/
 * @param norm should the data be normalized by mean/sd?
 */
public void write(double data[], boolean norm) {
    ByteOrder b = ByteOrder.nativeOrder();
    FileOutputStream fos;
    DataOutputStream dos;

    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    double mean = 0.0;
    double sd = 0.0;

    int n = 0;
    for (int k = 0; k < extz; k++) {
        for (int j = 0; j < exty; j++) {
            for (int i = 0; i < extx; i++) {
                int index = stride * (i + extx * (j + exty * k));
                // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                n++;
                if (data[index] < min) {
                    min = data[index];
                }
                if (data[index] > max) {
                    max = data[index];
                }
                mean += (data[index] - mean) / n;
            }
        }
    }

    n = 0;
    for (int k = 0; k < extz; k++) {
        for (int j = 0; j < exty; j++) {
            for (int i = 0; i < extx; i++) {
                int index = stride * (i + extx * (j + exty * k));
                // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                sd += pow(data[index] - mean, 2.0);
                n++;
            }
        }
    }
    sd = sqrt(sd / n);

    if (norm) {
        for (int k = 0; k < extz; k++) {
            for (int j = 0; j < exty; j++) {
                for (int i = 0; i < extx; i++) {
                    int index = stride * (i + extx * (j + exty * k));
                    data[index] = (data[index] - mean) / sd;
                }
            }
        }
        // recurse
        write(data, false);
    }

    try {
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\nwriting CCP4 map file: \"%s\"\n", filename));
            sb.append(String.format("map min: %g max: %g mean: %g standard dev.: %g", min, max, mean, sd));
            logger.info(sb.toString());
        }

        fos = new FileOutputStream(filename);
        dos = new DataOutputStream(fos);

        byte bytes[] = new byte[2048];
        int offset = 0;

        int imapdata;
        float fmapdata;
        String mapstr;

        // header
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        bb.order(b).putInt(extx);
        bb.order(b).putInt(exty);
        bb.order(b).putInt(extz);

        // mode (2 = reals, only one we accept)
        bb.order(b).putInt(2);

        bb.order(b).putInt(orix);
        bb.order(b).putInt(oriy);
        bb.order(b).putInt(oriz);
        bb.order(b).putInt(nx);
        bb.order(b).putInt(ny);
        bb.order(b).putInt(nz);

        bb.order(b).putFloat((float) crystal.a);
        bb.order(b).putFloat((float) crystal.b);
        bb.order(b).putFloat((float) crystal.c);
        bb.order(b).putFloat((float) crystal.alpha);
        bb.order(b).putFloat((float) crystal.beta);
        bb.order(b).putFloat((float) crystal.gamma);

        bb.order(b).putInt(1);
        bb.order(b).putInt(2);
        bb.order(b).putInt(3);

        bb.order(b).putFloat((float) min);
        bb.order(b).putFloat((float) max);
        bb.order(b).putFloat((float) mean);

        bb.order(b).putInt(crystal.spaceGroup.number);
        // bb.order(b).putInt(1);

        // symmetry bytes - should set this up at some point
        // imapdata = swap ? ByteSwap.swap(320) : 320;
        bb.order(b).putInt(80);

        bb.order(b).putInt(0);

        for (int i = 0; i < 12; i++) {
            bb.order(b).putFloat(0.0f);
        }

        for (int i = 0; i < 15; i++) {
            bb.order(b).putInt(0);
        }
        dos.write(bytes, offset, 208);
        bb.rewind();

        mapstr = "MAP ";
        dos.writeBytes(mapstr);

        // machine code: double, float, int, uchar
        // 0x4441 for LE, 0x1111 for BE
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            imapdata = 0x4441;
        } else {
            imapdata = 0x1111;
        }
        bb.order(b).putInt(imapdata);

        bb.order(b).putFloat((float) sd);

        bb.order(b).putInt(1);
        dos.write(bytes, offset, 12);

        StringBuilder sb = new StringBuilder();
        sb.append("map data from ffx");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dos.writeBytes(sb.toString());

        sb = new StringBuilder();
        while (sb.length() < 80) {
            sb.append(" ");
        }
        for (int i = 0; i < 9; i++) {
            dos.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append("x,y,z");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dos.writeBytes(sb.toString());

        bb.rewind();
        for (int k = 0; k < extz; k++) {
            for (int j = 0; j < exty; j++) {
                for (int i = 0; i < extx; i++) {
                    int index = stride * (i + extx * (j + exty * k));
                    // int index = k * (exty * (extx + 2)) + j * (extx + 2) + i;
                    fmapdata = (float) data[index];
                    bb.order(b).putFloat(fmapdata);
                    if (!bb.hasRemaining()) {
                        dos.write(bytes);
                        bb.rewind();
                    }
                }
            }
        }
        if (bb.position() > 0) {
            dos.write(bytes);
            bb.rewind();
        }

        dos.close();
    } catch (Exception e) {
        String message = "Fatal exception evaluating structure factors.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }
}