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:guru.benson.pinch.Pinch.java

/**
 * Parses the ZIP central directory from a byte buffer.
 *
 * @param data//  www .  j a va2  s  . c o m
 *     The byte buffer to be parsed.
 *
 * @return {@code true} if central directory was parsed, otherwise {@code false}
 */
private boolean parseEndOfCentralDirectory(byte[] data) {

    byte[] zipEndSignature = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)
            .putInt((int) ZipConstants.ENDSIG).array();

    // find start of ZIP archive signature.
    int index = KMPMatch.indexOf(data, zipEndSignature);

    if (index < 0) {
        return false;
    }

    // wrap our head around a part of the buffer starting with index.
    ByteBuffer buf = ByteBuffer.wrap(data, index, data.length - index);
    buf.order(ByteOrder.LITTLE_ENDIAN);

    /*
     * For ZIP header descriptions, see
     * http://en.wikipedia.org/wiki/ZIP_(file_format)#File_headers
     */

    // skip signature
    buf.getInt();
    // skip numberOfThisDisk
    buf.getShort();
    // skip diskWhereCentralDirectoryStarts =
    buf.getShort();
    // skip numberOfCentralDirectoriesOnThisDisk
    buf.getShort();

    entriesCount = buf.getShort();
    centralDirectorySize = buf.getInt();
    centralDirectoryOffset = buf.getInt();
    zipFileCommentLength = buf.getShort();

    return true;
}

From source file:au.org.ala.layers.grid.GridCacheBuilder.java

private static void writeGroupGRI(File file, ArrayList<Grid> group) {
    Grid g = group.get(0);//w  ww.j  av a  2  s. co m
    RandomAccessFile[] raf = new RandomAccessFile[group.size()];
    RandomAccessFile output = null;

    try {
        output = new RandomAccessFile(file, "rw");

        for (int i = 0; i < group.size(); i++) {
            raf[i] = new RandomAccessFile(group.get(i).filename + ".gri", "r");
        }

        int length = g.ncols * g.nrows;
        int size = 4;
        byte[] b = new byte[size * group.size() * g.ncols];
        float noDataValue = Float.MAX_VALUE * -1;

        byte[] bi = new byte[g.ncols * 8];
        float[][] rows = new float[group.size()][g.ncols];

        for (int i = 0; i < g.nrows; i++) {
            //read
            for (int j = 0; j < raf.length; j++) {
                nextRowOfFloats(rows[j], group.get(j).datatype, group.get(j).byteorderLSB, g.ncols, raf[j], bi,
                        (float) g.nodatavalue);
            }

            //write
            ByteBuffer bb = ByteBuffer.wrap(b);
            bb.order(ByteOrder.LITTLE_ENDIAN);

            for (int k = 0; k < g.ncols; k++) {
                for (int j = 0; j < raf.length; j++) {
                    //float f = getNextValue(raf[j], group.get(j));
                    float f = rows[j][k];
                    if (Float.isNaN(f)) {
                        bb.putFloat(noDataValue);
                    } else {
                        bb.putFloat(f);
                    }
                }
            }
            output.write(b);
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        for (int i = 0; i < raf.length; i++) {
            if (raf[i] != null) {
                try {
                    raf[i].close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:ome.formats.importer.OMEROWrapper.java

/**
 * Obtains an object which represents a given sub-image of a plane within
 * the file.//from  w  w  w .  java2 s.  c  om
 * @param id The path to the file.
 * @param planeNumber The plane or section within the file to obtain.
 * @param buf Pre-allocated buffer which has a <i>length</i> that can fit
 * the byte count of the sub-image.
 * @param x X coordinate of the upper-left corner of the sub-image
 * @param y Y coordinate of the upper-left corner of the sub-image
 * @param w width of the sub-image
 * @param h height of the sub-image
 * @return an object which represents the sub-image of the plane.
 * @throws FormatException If there is an error parsing the file.
 * @throws IOException If there is an error reading from the file or
 * acquiring permissions to read the file.
 */
public PixelData openPlane2D(String id, int planeNumber, byte[] buf, int x, int y, int w, int h)
        throws FormatException, IOException {
    // FIXME: HACK! The ChannelSeparator isn't exactly what one would call
    // "complete" so we have to work around the fact that it still copies
    // all of the plane data (all three channels) from the file if the file
    // is RGB.
    ByteBuffer plane;
    if (iReader.isRGB() || isLeicaReader()) {
        // System.err.println("RGB, not using cached buffer.");
        byte[] bytePlane = openBytes(planeNumber, x, y, w, h);
        plane = ByteBuffer.wrap(bytePlane);
    } else {
        // System.err.println("Not RGB, using cached buffer.");
        plane = ByteBuffer.wrap(openBytes(planeNumber, buf, x, y, w, h));
    }
    plane.order(isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
    return new PixelData(FormatTools.getPixelTypeString(getPixelType()), plane);
}

From source file:org.ros.internal.transport.MessageQueueIntegrationTest.java

private Channel buildServerChannel() {
    TopicParticipantManager topicParticipantManager = new TopicParticipantManager();
    ServiceManager serviceManager = new ServiceManager();
    NioServerSocketChannelFactory channelFactory = new NioServerSocketChannelFactory(executorService,
            executorService);//from  w  w  w. j a v  a  2 s. c  o  m
    ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
    bootstrap.setOption("child.bufferFactory", new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN));
    bootstrap.setOption("child.keepAlive", true);
    ChannelGroup serverChannelGroup = new DefaultChannelGroup();
    TcpRosServerPipelineFactory serverPipelineFactory = new TcpRosServerPipelineFactory(serverChannelGroup,
            topicParticipantManager, serviceManager) {
        @Override
        public ChannelPipeline getPipeline() {
            ChannelPipeline pipeline = super.getPipeline();
            // We're not interested firstIncomingMessageQueue testing the
            // handshake here. Removing it means connections are established
            // immediately.
            pipeline.remove(TcpRosServerPipelineFactory.HANDSHAKE_HANDLER);
            pipeline.addLast("ServerHandler", new ServerHandler());
            return pipeline;
        }
    };
    bootstrap.setPipelineFactory(serverPipelineFactory);
    Channel serverChannel = bootstrap.bind(new InetSocketAddress(0));
    return serverChannel;
}

From source file:com.yobidrive.diskmap.needles.Needle.java

public boolean getNeedleHeaderFromBuffer(ByteBuffer input) throws Exception {
    try {/*  w  w  w  .j  a  v a 2s. co m*/
        // Reinit needle
        keyBytes = null;
        version = null;
        flags = 0x00;
        size = 0;
        data = null;
        previousNeedle = null; // Chaining
        readBytes = 0;
        // Processes reading
        input.rewind();
        int startPosition = input.position();
        int magic = input.getInt();
        if (magic == MAGICSTART_BADENDIAN) {
            if (input.order().equals(ByteOrder.BIG_ENDIAN))
                input.order(ByteOrder.LITTLE_ENDIAN);
            else
                input.order(ByteOrder.BIG_ENDIAN);
        } else if (magic != MAGICSTART) {
            logger.error("Buffer not starting with needle");
            return false;
        }
        needleNumber = input.getLong();
        flags = input.get();
        int keyLen = input.getInt();
        if (keyLen > 2028) {
            logger.error("Crazy needle key len");
            return false;
        }
        keyBytes = new byte[keyLen];
        input.get(keyBytes);
        int versionLen = input.getInt();
        if (versionLen > 1024 * 16) {
            logger.error("Crazy needle version len");
            return false;
        }
        if (versionLen == 0)
            version = null;
        else {
            byte[] versionBytes = new byte[versionLen];
            input.get(versionBytes);
            version = new VectorClock(versionBytes);
        }
        int previousLogNumber = input.getInt(); // Chaining
        long previousNeedleOffset = input.getLong(); // Chaining
        if (previousLogNumber != -1 && previousNeedleOffset != -1L) {
            previousNeedle = new NeedlePointer();
            previousNeedle.setNeedleFileNumber(previousLogNumber);
            previousNeedle.setNeedleOffset(previousNeedleOffset);
        }
        originalFileNumber = input.getInt(); // Original needle location (for cleaning)
        originalSize = input.getInt(); // Original needle size (for cleaning)
        size = input.getInt();

        readBytes = input.position() - startPosition;
        input.rewind();
        // input.mark() ;
        return true;
    } catch (BufferUnderflowException bue) {
        return false;
    }
}

From source file:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}/* w  w  w.j av a2 s . c o  m*/
 */
@Override
public boolean readFile(String filename, RealSpaceRefinementData refinementdata,
        CompositeConfiguration properties) {

    int imapdata;
    double cella, cellb, cellc, cellalpha, cellbeta, cellgamma;
    String stampstr;

    ByteOrder b = ByteOrder.nativeOrder();

    FileInputStream fis;
    DataInputStream dis;

    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 {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

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

        imapdata = bb.order(ByteOrder.BIG_ENDIAN).getInt();
        stampstr = Integer.toHexString(imapdata);
        // System.out.println("stamp: " + stampstr);
        switch (stampstr.charAt(0)) {
        case '1':
        case '3':
            if (b.equals(ByteOrder.LITTLE_ENDIAN)) {
                b = ByteOrder.BIG_ENDIAN;
            }
            break;
        case '4':
            if (b.equals(ByteOrder.BIG_ENDIAN)) {
                b = ByteOrder.LITTLE_ENDIAN;
            }
            break;
        }

        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("\nOpening CCP4 map: %s\n", filename));
            sb.append(String.format("file type (machine stamp): %s\n", stampstr));
            logger.info(sb.toString());
        }

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

    try {
        fis = new FileInputStream(filename);
        dis = new DataInputStream(fis);

        byte bytes[] = new byte[2048];

        dis.read(bytes, 0, 1024);
        ByteBuffer bb = ByteBuffer.wrap(bytes);

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

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

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

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

        cella = bb.order(b).getFloat();
        cellb = bb.order(b).getFloat();
        cellc = bb.order(b).getFloat();
        cellalpha = bb.order(b).getFloat();
        cellbeta = bb.order(b).getFloat();
        cellgamma = bb.order(b).getFloat();

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

        min = bb.order(b).getFloat();
        max = bb.order(b).getFloat();
        mean = bb.order(b).getFloat();

        int sg = bb.order(b).getInt();

        int nsymb = bb.order(b).getInt();

        int skew = bb.order(b).getInt();

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

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

        byte word[] = new byte[2048];
        bb.order(b).get(word, 0, 4);
        String mapstr = new String(word);
        // System.out.println("MAP?: " + mapstr);

        sd = bb.order(b).getFloat();
        rmsd = bb.order(b).getFloat();

        /*
         System.out.println("col: " + ori[0] + " " + ext[0] + " " + ni[0]);
         System.out.println("row: " + ori[1] + " " + ext[1] + " " + ni[1]);
         System.out.println("sec: " + ori[2] + " " + ext[2] + " " + ni[2]);
         System.out.println("order: " + axisi[0] + " " + axisi[1] + " " + axisi[2]);
         System.out.println("min: " + min + " max: " + max + " mean: " + mean);
         System.out.println("sd: " + sd + " rmsd: " + rmsd);
         System.out.println("sg: " + sg);
         System.out.println("a: " + cella + " b: " + cellb + " c: " + cellc
         + " alpha: " + cellalpha + " beta: " + cellbeta + " gamma: " + cellgamma);
         */
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("  column origin: %d extent: %d\n", ori[0], ext[0]));
            sb.append(String.format("  row origin: %d extent: %d\n", ori[1], ext[1]));
            sb.append(String.format("  section origin: %d 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 (name: %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 = bb.order(b).getInt();

        // System.out.println("nsymb: " + nsymb + " nlabel: " + nlabel);
        for (int i = 0; i < 10; i++) {
            bb.order(b).get(word, 0, 80);
            mapstr = new String(word);
            // System.out.println("label " + i + " : " + mapstr);
        }

        if (nsymb > 0) {
            bb.rewind();
            dis.read(bytes, 0, nsymb);
            for (int i = 0; i < nsymb / 80; i += 80) {
                bb.order(b).get(word, 0, 80);
                mapstr = new String(word);
                // System.out.println("symm: " + mapstr);
            }
        }

        bb.rewind();
        dis.read(bytes, 0, 2048);
        refinementdata.data = new double[ext[0] * ext[1] * ext[2]];
        int ijk[] = new int[3];
        int index, x, y, z;
        refinementdata.ori[0] = ori[axisi[0]];
        refinementdata.ori[1] = ori[axisi[1]];
        refinementdata.ori[2] = ori[axisi[2]];
        int nx = ext[axisi[0]];
        int ny = ext[axisi[1]];
        int nz = ext[axisi[2]];
        refinementdata.ext[0] = nx;
        refinementdata.ext[1] = ny;
        refinementdata.ext[2] = nz;
        refinementdata.ni[0] = ni[0];
        refinementdata.ni[1] = ni[1];
        refinementdata.ni[2] = 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.data[index] = bb.order(b).getFloat();
                    if (!bb.hasRemaining()) {
                        bb.rewind();
                        dis.read(bytes, 0, 2048);
                    }
                }
            }
        }
        fis.close();
    } catch (Exception e) {
        String message = "Fatal exception reading CCP4 map.\n";
        logger.log(Level.SEVERE, message, e);
        System.exit(-1);
    }

    return true;
}

From source file:com.mmj.app.common.util.IPTools.java

/**
 * ????s?IP// w  ww  .ja  v  a  2 s. com
 * 
 * @param s ?
 * @return ?IPEntryList
 */
public List<IPEntry> getIPEntries(String s) {
    List<IPEntry> ret = new ArrayList<IPEntry>();
    try {
        // IP?
        if (mbb == null) {
            FileChannel fc = ipFile.getChannel();
            mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
            mbb.order(ByteOrder.LITTLE_ENDIAN);
        }

        int endOffset = (int) ipEnd;
        for (int offset = (int) ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
            int temp = readInt3(offset);
            if (temp != -1) {
                IPLocation loc = getIPLocation(temp);
                // ???s??List
                if (loc.country.indexOf(s) != -1 || loc.area.indexOf(s) != -1) {
                    IPEntry entry = new IPEntry();
                    entry.country = loc.country;
                    entry.area = loc.area;
                    // IP
                    readIP(offset - 4, b4);
                    entry.beginIp = getIpStringFromBytes(b4);
                    // ?IP
                    readIP(temp, b4);
                    entry.endIp = getIpStringFromBytes(b4);
                    // 
                    ret.add(entry);
                }
            }
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    return ret;
}

From source file:org.jmangos.sniffer.network.model.impl.WOWNetworkChannel.java

@Override
public void onResiveClientData(final long frameNumber, final byte[] buffer) {
    final ByteBuffer bytebuf = ByteBuffer.wrap(buffer);
    long opcode = 0;
    long size = 0;
    byte[] data;/*from w  ww  .j av  a  2  s  . co m*/
    bytebuf.order(ByteOrder.LITTLE_ENDIAN);
    if (getChannelState().contains(State.AUTHED)) {
        final long header = bytebuf.getInt() & 0xFFFFFFFF;
        size = header >> 13;
        opcode = (header & 0x1FFF);
        data = new byte[(int) size];
        bytebuf.get(data);
    } else {
        size = bytebuf.getShort();
        opcode = bytebuf.getInt();
        data = new byte[(int) size - 4];
        bytebuf.get(data);
        // old (opcode == 0x1a72) | (opcode == 0x3f3)
        if ((opcode == 0x1aa1) | (opcode == 0x9f1)) {
            this.log.debug("Init cryptography system for channel {}", this.getChannelId());
            addChannelState(State.AUTHED);
            this.csPacketBuffer.getCrypt().init(this.woWKeyReader.getKey());
            this.scPacketBuffer.getCrypt().init(this.woWKeyReader.getKey());
        }
    }
    this.log.debug(String.format("Frame: %d; Resive packet %s Opcode: 0x%x\n", frameNumber, "CMSG", opcode));
    for (final PacketLogHandler logger : this.packetLoggers) {
        logger.onDecodePacket(this, Direction.CLIENT, (int) size, (int) opcode, data, (int) frameNumber);
    }
}

From source file:com.monitor.baseservice.utils.XCodeUtil.java

public static byte[] longToByteArray(long value) {
    ByteBuffer bb = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.putLong(value);//from  ww  w  .  ja  v  a 2  s.c  om
    return bb.array();
}

From source file:edu.tsinghua.lumaqq.IPSeeker.java

/**
 * ????s?IP//  www . ja  v a  2  s.  com
 * @param s ?
 * @return ?IPEntryList
 */
public List<IPEntry> getIPEntries(String s) {
    List<IPEntry> ret = new ArrayList<IPEntry>();
    try {
        // IP?
        if (mbb == null) {
            FileChannel fc = ipFile.getChannel();
            mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
            mbb.order(ByteOrder.LITTLE_ENDIAN);
        }

        int endOffset = (int) ipEnd;
        for (int offset = (int) ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
            int temp = readInt3(offset);
            if (temp != -1) {
                IPLocation ipLoc = getIPLocation(temp);
                // ???s??List
                if (ipLoc.country.indexOf(s) != -1 || ipLoc.area.indexOf(s) != -1) {
                    IPEntry entry = new IPEntry();
                    entry.country = ipLoc.country;
                    entry.area = ipLoc.area;
                    // IP
                    readIP(offset - 4, b4);
                    entry.beginIp = Util.getIpStringFromBytes(b4);
                    // ?IP
                    readIP(temp, b4);
                    entry.endIp = Util.getIpStringFromBytes(b4);
                    // 
                    ret.add(entry);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage());
    }
    return ret;
}