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:org.jtransforms.fft.DoubleFFT_1DTest.java

/**
 * Read the binary reference data files generated with FFTW. The structure
 * of these files is very simple: double values are written linearly (little
 * endian)./* w ww.  j a  v a 2s  .  com*/
 *
 * @param name
 *             the file name
 * @param data
 *             the array to be updated with the data read (the size of this
 *             array gives the number of <code>double</code> to be retrieved
 */
public void readData(final String name, final DoubleLargeArray data) {
    try {
        final File f = new File(getClass().getClassLoader().getResource(name).getFile());
        final FileInputStream fin = new FileInputStream(f);
        final FileChannel fc = fin.getChannel();
        final ByteBuffer buffer = ByteBuffer.allocate(8 * (int) data.length());
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        fc.read(buffer);
        for (int i = 0; i < data.length(); i++) {
            data.setDouble(i, buffer.getDouble(8 * i));
        }
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.apache.nifi.processors.evtx.parser.BinaryReader.java

/**
 * Reads 2 bytes in little endian order and returns the int value
 *
 * @return the value// w  w  w  .  j  av a  2  s  .c  om
 */
public int readWord() {
    byte[] bytes = new byte[4];
    readBytes(bytes, 0, 2);
    return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

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

/**
 * Extract all ZipEntries from the ZIP central directory.
 *
 * @param buf//from  w  w  w . j av  a2 s  . c  om
 *     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:au.org.ala.delta.io.BinFile.java

public void writeByte(byte b) {
    try {//from   w w  w. j a v  a2 s.co  m
        // _file.write(b);
        ByteBuffer bb = ByteBuffer.allocate(1);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.put(b);
        bb.position(0);
        _channel.write(bb);
    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
}

From source file:com.codestation.henkakuserver.HenkakuServer.java

/**
 * Finalize the exploit with the addesses from the device
 *
 * @param exploit payload compiled code/*from ww w  .  j  a  v a2s . c o m*/
 * @param params  list of addresses from the device
 * @return patched shellcode
 * @throws Exception
 */
private byte[] patchExploit(byte[] exploit, Map<String, String> params) throws Exception {

    if (params.size() != 7) {
        throw new Exception("invalid argument count");
    }

    ArrayList<Long> args = new ArrayList<>();
    args.add(0L);

    for (int i = 1; i <= 7; ++i) {
        String arg = String.format("a%s", i);
        if (params.containsKey(arg)) {
            args.add(Long.parseLong(params.get(arg), 16));
        } else {
            throw new Exception(String.format("argument %s is missing", arg));
        }
    }

    byte[] copy = new byte[exploit.length];
    System.arraycopy(exploit, 0, copy, 0, exploit.length);

    ByteBuffer buf = ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN);
    int size_words = buf.getInt(0);

    int dsize = buf.getInt(4 + 0x10);
    int csize = buf.getInt(4 + 0x20);

    long data_base = args.get(1) + csize;

    for (int i = 1; i < size_words; ++i) {
        long add = 0;
        byte x = buf.get(size_words * 4 + 4 + i - 1);

        if (x == 1) {
            add = data_base;
        } else if (x != 0) {
            add = args.get(x);
        }

        buf.putInt(i * 4, buf.getInt(i * 4) + (int) add);
    }

    byte[] out = new byte[dsize + csize];

    System.arraycopy(copy, 4 + 0x40, out, csize, dsize);
    System.arraycopy(copy, 4 + 0x40 + dsize, out, 0, csize);

    return out;
}

From source file:ffx.xray.parsers.MTZFilter.java

/**
 * {@inheritDoc}// w  w w.j  ava2  s .c  om
 */
@Override
public ReflectionList getReflectionList(File mtzFile, CompositeConfiguration properties) {
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;
    try {
        fileInputStream = new FileInputStream(mtzFile);
        dataInputStream = new DataInputStream(fileInputStream);

        byte headerOffset[] = new byte[4];
        byte bytes[] = new byte[80];
        int offset = 0;

        // Eat "MTZ" title.
        dataInputStream.read(bytes, offset, 4);
        String mtzstr = new String(bytes);

        // Header offset.
        dataInputStream.read(headerOffset, offset, 4);

        // Machine stamp.
        dataInputStream.read(bytes, offset, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int stamp = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        String stampstr = Integer.toHexString(stamp);
        switch (stampstr.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        byteBuffer = ByteBuffer.wrap(headerOffset);
        int headerOffsetI = byteBuffer.order(byteOrder).getInt();

        // skip to header and parse
        dataInputStream.skipBytes((headerOffsetI - 4) * 4);

        for (Boolean parsing = true; parsing; dataInputStream.read(bytes, offset, 80)) {
            mtzstr = new String(bytes);
            parsing = parseHeader(mtzstr);
        }
    } catch (EOFException e) {
        String message = " MTZ end of file reached.";
        logger.log(Level.WARNING, message, e);
        return null;
    } catch (IOException e) {
        String message = " MTZ IO exception.";
        logger.log(Level.WARNING, message, e);
        return null;
    }

    // column identifiers
    foString = sigFoString = rFreeString = null;
    if (properties != null) {
        foString = properties.getString("fostring", null);
        sigFoString = properties.getString("sigfostring", null);
        rFreeString = properties.getString("rfreestring", null);
    }
    h = k = l = fo = sigFo = rFree = -1;
    fPlus = sigFPlus = fMinus = sigFMinus = rFreePlus = rFreeMinus = -1;
    fc = phiC = -1;
    boolean print = false;
    parseColumns(print);
    parseFcColumns(print);

    if (fo < 0 && fPlus < 0 && sigFo < 0 && sigFPlus < 0 && fc < 0 && phiC < 0) {
        logger.info(" The MTZ header contains insufficient information to generate the reflection list.");
        logger.info(" For non-default column labels set fostring/sigfostring in the properties file.");
        return null;
    }

    Column column;
    if (fo > 0) {
        column = (Column) columns.get(fo);
    } else if (fPlus > 0) {
        column = (Column) columns.get(fPlus);
    } else {
        column = (Column) columns.get(fc);
    }
    Dataset dataSet = (Dataset) dataSets.get(column.id - dsetOffset);

    if (logger.isLoggable(Level.INFO)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Reading %s\n\n", mtzFile.getName()));
        sb.append(format(" Setting up reflection list based on MTZ file.\n"));
        sb.append(format("  Space group number: %d (name: %s)\n", spaceGroupNum,
                SpaceGroup.spaceGroupNames[spaceGroupNum - 1]));
        sb.append(format("  Resolution:         %8.3f\n", 0.999999 * resHigh));
        sb.append(format("  Cell:               %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", dataSet.cell[0],
                dataSet.cell[1], dataSet.cell[2], dataSet.cell[3], dataSet.cell[4], dataSet.cell[5]));
        logger.info(sb.toString());
    }

    Crystal crystal = new Crystal(dataSet.cell[0], dataSet.cell[1], dataSet.cell[2], dataSet.cell[3],
            dataSet.cell[4], dataSet.cell[5], SpaceGroup.spaceGroupNames[spaceGroupNum - 1]);

    double sampling = 0.6;
    if (properties != null) {
        sampling = properties.getDouble("sampling", 0.6);
    }
    Resolution resolution = new Resolution(0.999999 * resHigh, sampling);

    return new ReflectionList(crystal, resolution, properties);
}

From source file:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from   ww  w .  j  a va  2 s  .  c  om*/
 */
@Override
public boolean readFile(String filename, RealSpaceRefinementData refinementdata,
        CompositeConfiguration properties) {

    int imapData;
    double cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma;
    String stampString;

    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileInputStream fileInputStream;
    DataInputStream dataInputStream;

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

    // First determine byte order of file versus system
    try {
        fileInputStream = new FileInputStream(filename);
        dataInputStream = new DataInputStream(fileInputStream);

        dataInputStream.skipBytes(212);
        byte bytes[] = new byte[4];
        dataInputStream.read(bytes, 0, 4);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt();
        stampString = Integer.toHexString(imapData);
        switch (stampString.charAt(0)) {
        case '1':
        case '3':
            if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) {
                byteOrder = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) {
                byteOrder = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\n Opening CCP4 map: %s\n", filename));
            //sb.append(String.format("file type (machine stamp): %s\n", stampString));
            logger.info(sb.toString());
        }

        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    try {
        fileInputStream = new FileInputStream(filename);
        dataInputStream = new DataInputStream(fileInputStream);

        byte bytes[] = new byte[2048];

        dataInputStream.read(bytes, 0, 1024);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);

        int ext[] = new int[3];
        ext[0] = byteBuffer.order(byteOrder).getInt();
        ext[1] = byteBuffer.order(byteOrder).getInt();
        ext[2] = byteBuffer.order(byteOrder).getInt();

        // mode (2 = reals, only one we accept)
        int mode = byteBuffer.order(byteOrder).getInt();

        int ori[] = new int[3];
        ori[0] = byteBuffer.order(byteOrder).getInt();
        ori[1] = byteBuffer.order(byteOrder).getInt();
        ori[2] = byteBuffer.order(byteOrder).getInt();

        int ni[] = new int[3];
        ni[0] = byteBuffer.order(byteOrder).getInt();
        ni[1] = byteBuffer.order(byteOrder).getInt();
        ni[2] = byteBuffer.order(byteOrder).getInt();

        cellA = byteBuffer.order(byteOrder).getFloat();
        cellB = byteBuffer.order(byteOrder).getFloat();
        cellC = byteBuffer.order(byteOrder).getFloat();
        cellAlpha = byteBuffer.order(byteOrder).getFloat();
        cellBeta = byteBuffer.order(byteOrder).getFloat();
        cellGamma = byteBuffer.order(byteOrder).getFloat();

        int axisi[] = new int[3];
        for (int i = 0; i < 3; i++) {
            int axis = byteBuffer.order(byteOrder).getInt();
            switch (axis) {
            case 1:
                axisi[0] = i;
                break;
            case 2:
                axisi[1] = i;
                break;
            case 3:
                axisi[2] = i;
                break;
            }
        }

        min = byteBuffer.order(byteOrder).getFloat();
        max = byteBuffer.order(byteOrder).getFloat();
        mean = byteBuffer.order(byteOrder).getFloat();
        int sg = byteBuffer.order(byteOrder).getInt();
        int nsymb = byteBuffer.order(byteOrder).getInt();
        int skew = byteBuffer.order(byteOrder).getInt();

        for (int i = 0; i < 12; i++) {
            byteBuffer.order(byteOrder).getFloat();
        }

        for (int i = 0; i < 15; i++) {
            byteBuffer.order(byteOrder).getInt();
        }

        byte word[] = new byte[2048];
        byteBuffer.order(byteOrder).get(word, 0, 4);
        String mapString = new String(word);
        sd = byteBuffer.order(byteOrder).getFloat();
        rmsd = byteBuffer.order(byteOrder).getFloat();

        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("  Column origin:  %d\t Extent: %d\n", ori[0], ext[0]));
            sb.append(String.format("  Row origin:     %d\t Extent: %d\n", ori[1], ext[1]));
            sb.append(String.format("  Section origin: %d\t Extent: %d\n", ori[2], ext[2]));
            sb.append(String.format("  Axis order:     %d %d %d\n", axisi[0], axisi[1], axisi[2]));
            sb.append(String.format("  Number of X, Y, Z columns: %d %d %d\n", ni[0], ni[1], ni[2]));
            sb.append(String.format("  Spacegroup:     %d (%s)\n", sg, SpaceGroup.spaceGroupNames[sg - 1]));
            sb.append(String.format("  Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", cellA, cellB, cellC,
                    cellAlpha, cellBeta, cellGamma));
            logger.info(sb.toString());
        }

        int nlabel = byteBuffer.order(byteOrder).getInt();
        for (int i = 0; i < 10; i++) {
            byteBuffer.order(byteOrder).get(word, 0, 80);
            mapString = new String(word);
        }

        if (nsymb > 0) {
            byteBuffer.rewind();
            dataInputStream.read(bytes, 0, nsymb);
            for (int i = 0; i < nsymb / 80; i += 80) {
                byteBuffer.order(byteOrder).get(word, 0, 80);
                mapString = new String(word);
            }
        }

        byteBuffer.rewind();
        dataInputStream.read(bytes, 0, 2048);
        refinementdata.setData(new double[ext[0] * ext[1] * ext[2]]);
        int ijk[] = new int[3];
        int index, x, y, z;
        refinementdata.setOrigin(ori[axisi[0]], ori[axisi[1]], ori[axisi[2]]);
        int nx = ext[axisi[0]];
        int ny = ext[axisi[1]];
        int nz = ext[axisi[2]];
        refinementdata.setExtent(nx, ny, nz);
        refinementdata.setNI(ni[0], ni[1], ni[2]);
        for (ijk[2] = 0; ijk[2] < ext[2]; ijk[2]++) {
            for (ijk[1] = 0; ijk[1] < ext[1]; ijk[1]++) {
                for (ijk[0] = 0; ijk[0] < ext[0]; ijk[0]++) {
                    x = ijk[axisi[0]];
                    y = ijk[axisi[1]];
                    z = ijk[axisi[2]];
                    index = x + nx * (y + ny * z);
                    refinementdata.getData()[index] = byteBuffer.order(byteOrder).getFloat();
                    if (!byteBuffer.hasRemaining()) {
                        byteBuffer.rewind();
                        dataInputStream.read(bytes, 0, 2048);
                    }
                }
            }
        }
        fileInputStream.close();
    } catch (Exception e) {
        String message = " Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
    }

    return true;
}

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private void patchGame() throws IOException {
    /*//from  ww  w. j  a  va2 s  .  co m
     * Custom patch format (config/game-patch.bin) is as follows:
     * 0x8 byte little endian: Address in game image to start patching
     * 0x8 byte little endian: Length of patch
     * If there are more patches, repeat after reading the length of patch
     * Note that all games will be patched the same way, so if a game is broken before patching, it will still be broken!
     */
    nextStep("Patching game.");
    File gamePatch = new File(mTempDir, "/config/game-patch.bin");
    if (!gamePatch.exists())
        return;
    Logger.info("Making a copy of game.");
    File tempGame = new File(mTempDir, "game.iso");
    FileUtils.copyFile(mInputFile, tempGame);
    RandomAccessFile game = new RandomAccessFile(tempGame, "rw");
    InputStream patch = new FileInputStream(gamePatch);
    while (true) {
        byte[] rawPatchAddr = new byte[8];
        byte[] rawPatchLen = new byte[8];
        if (patch.read(rawPatchAddr) + patch.read(rawPatchLen) < rawPatchAddr.length + rawPatchLen.length)
            break;
        ByteBuffer bb = ByteBuffer.wrap(rawPatchAddr);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchAddr = bb.getLong();
        bb = ByteBuffer.wrap(rawPatchLen);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchLen = bb.getLong();

        game.seek(patchAddr);
        while (patchLen-- > 0) {
            game.write(patch.read());
        }
    }
    mInputFile = tempGame;
    game.close();
    patch.close();
    Logger.debug("Done patching game.");
}

From source file:au.org.ala.delta.io.BinaryKeyFile.java

/**
 * Designed to allow headers and index records to be overwritten.
 * /*from   w w w  .  ja v  a2 s. c o  m*/
 * @param recordNumber
 *            the first (of possibily many, depending on the number of
 *            values) record to be overwritten.
 * @param values
 *            the values to write, starting at record, recordNumber..
 */
public void overwriteRecord(int recordNumber, List<Integer> values) {
    if (!_occupiedRecords.contains(recordNumber)) {
        throw new IllegalArgumentException("Record " + recordNumber + " has not been allocated.");
    }
    ByteBuffer bytes = ByteBuffer.allocate(values.size() * SIZE_INT_IN_BYTES);
    bytes.order(ByteOrder.LITTLE_ENDIAN);
    for (int value : values) {
        bytes.putInt(value);
    }
    seekToRecord(recordNumber, 0);
    write(bytes.array());
}

From source file:au.org.ala.delta.io.BinFile.java

public void writeShort(short value) {
    ByteBuffer buffer = ByteBuffer.allocate(2);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.putShort(value);//w w  w  . jav a  2  s.  co m
    writeBytes(buffer);
}