Example usage for java.nio ByteOrder BIG_ENDIAN

List of usage examples for java.nio ByteOrder BIG_ENDIAN

Introduction

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

Prototype

ByteOrder BIG_ENDIAN

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

Click Source Link

Document

This constant represents big endian.

Usage

From source file:org.onlab.util.ImmutableByteSequenceTest.java

@Test
public void testEndianness() throws Exception {

    long longValue = RandomUtils.nextLong();

    // creates a new sequence from a big-endian buffer
    ByteBuffer bbBigEndian = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).putLong(longValue);
    ImmutableByteSequence bsBufferCopyBigEndian = ImmutableByteSequence.copyFrom(bbBigEndian);

    // creates a new sequence from a little-endian buffer
    ByteBuffer bbLittleEndian = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(longValue);
    ImmutableByteSequence bsBufferCopyLittleEndian = ImmutableByteSequence.copyFrom(bbLittleEndian);

    // creates a new sequence from primitive type
    ImmutableByteSequence bsLongCopy = ImmutableByteSequence.copyFrom(longValue);

    new EqualsTester()
            // big-endian byte array cannot be equal to little-endian array
            .addEqualityGroup(bbBigEndian.array()).addEqualityGroup(bbLittleEndian.array())
            // all byte sequences must be equal
            .addEqualityGroup(bsBufferCopyBigEndian, bsBufferCopyLittleEndian, bsLongCopy)
            // byte buffer views of all sequences must be equal
            .addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer(),
                    bsBufferCopyLittleEndian.asReadOnlyBuffer(), bsLongCopy.asReadOnlyBuffer())
            // byte buffer orders of all sequences must be ByteOrder.BIG_ENDIAN
            .addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer().order(),
                    bsBufferCopyLittleEndian.asReadOnlyBuffer().order(), bsLongCopy.asReadOnlyBuffer().order(),
                    ByteOrder.BIG_ENDIAN)
            .testEquals();//w  ww.  j av  a  2s  .  c o m
}

From source file:Main.java

private static byte[] encodeUrnUuid(String urn, int position, ByteBuffer bb) {
    String uuidString = urn.substring(position, urn.length());
    UUID uuid;/*  w w  w.j  ava 2 s  .c  om*/
    try {
        uuid = UUID.fromString(uuidString);
    } catch (IllegalArgumentException e) {
        //Log.w(TAG, "encodeUrnUuid invalid urn:uuid format - " + urn);
        return null;
    }
    // UUIDs are ordered as byte array, which means most significant first
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return byteBufferToArray(bb);
}

From source file:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}//from   w w w .j a va 2 s.  c  o m
 */
@Override
public Crystal getCrystal(String filename, CompositeConfiguration properties) {
    int imapdata;
    int sg = -1;
    double cella = -1.0;
    double cellb = -1.0;
    double cellc = -1.0;
    double cellalpha = -1.0;
    double cellbeta = -1.0;
    double cellgamma = -1.0;

    ByteOrder b = ByteOrder.nativeOrder();

    FileInputStream fis;
    DataInputStream dis;

    // 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();
        String 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;
        }
        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);

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

        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();

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

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

    return new Crystal(cella, cellb, cellc, cellalpha, cellbeta, cellgamma, SpaceGroup.spaceGroupNames[sg - 1]);
}

From source file:ffx.realspace.CCP4MapFilter.java

/**
 * {@inheritDoc}/*from   w ww  . ja v a 2  s  .  c  om*/
 */
@Override
public Crystal getCrystal(String fileName, CompositeConfiguration properties) {
    int imapData;
    int spaceGroup = -1;
    double cellA = -1.0;
    double cellB = -1.0;
    double cellC = -1.0;
    double cellAlpha = -1.0;
    double cellBeta = -1.0;
    double cellGamma = -1.0;

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

    // 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();
        String 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;
        }
        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);

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

        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();

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

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

    return new Crystal(cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma,
            SpaceGroup.spaceGroupNames[spaceGroup - 1]);
}

From source file:org.apache.hadoop.hbase.filter.DirectoryRowFilter.java

public static DirectoryRowFilter parseFrom(final byte[] pbBytes) throws DeserializationException {

    ByteBuffer bb = ByteBuffer.wrap(pbBytes).order(ByteOrder.BIG_ENDIAN);

    DirectoryRowFilter filter = new DirectoryRowFilter();

    filter.instanceModulus = bb.getLong();
    filter.instanceRemainder = bb.getLong();
    filter.threadModulus = bb.getLong();
    filter.threadRemainder = bb.getLong();

    return filter;
}

From source file:org.red5.io.mp3.impl.MP3Reader.java

/**
 * Creates reader from file input stream
 * @param stream          File input stream source
 *///from   ww w  .  ja  v a  2  s.  c  o  m
public MP3Reader(File file) throws FileNotFoundException {
    this.file = file;
    fis = new FileInputStream(file);
    // Grab file channel and map it to memory-mapped byte buffer in read-only mode
    channel = fis.getChannel();
    try {
        mappedFile = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    } catch (IOException e) {
        log.error("MP3Reader :: MP3Reader ::>\n", e);
    }

    // Use Big Endian bytes order
    mappedFile.order(ByteOrder.BIG_ENDIAN);
    // Wrap mapped byte buffer to MINA buffer
    in = ByteBuffer.wrap(mappedFile);
    // Analyze keyframes data
    analyzeKeyFrames();
    firstFrame = true;

    // Process ID3v2 header if present
    processID3v2Header();

    // Create file metadata object
    fileMeta = createFileMeta();

    // MP3 header is length of 32 bits, that is, 4 bytes
    // Read further if there's still data
    if (in.remaining() > 4) {
        // Look to next frame
        searchNextFrame();
        // Set position
        int pos = in.position();
        // Read header...
        // Data in MP3 file goes header-data-header-data...header-data
        MP3Header header = readHeader();
        // Set position
        in.position(pos);
        // Check header
        if (header != null) {
            checkValidHeader(header);
        } else {
            throw new RuntimeException("No initial header found.");
        }
    }
}

From source file:org.openspaces.memcached.protocol.binary.MemcachedBinaryResponseEncoder.java

public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryOp bcmd, ChannelBuffer extrasBuffer,
        ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue,
        long casUnique) {
    // take the ResponseMessage and turn it into a binary payload.
    ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
    header.writeByte((byte) 0x81); // magic
    header.writeByte(bcmd.getCode()); // opcode
    short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() : 0);

    header.writeShort(keyLength);/*from  w w  w  .  j a  va  2 s.co  m*/
    int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0;
    header.writeByte((byte) extrasLength); // extra length = flags + expiry
    header.writeByte((byte) 0); // data type unused
    header.writeShort(responseCode); // status code

    int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0;
    header.writeInt(dataLength + keyLength + extrasLength); // data length
    header.writeInt(opaqueValue); // opaque

    header.writeLong(casUnique);

    return header;
}

From source file:nl.salp.warcraft4j.util.ChecksumTest.java

@Test
public void shouldTrimToSizeUsingBigEndianess() {
    Checksum trimmed = checksum.trim(TRIMMED_LENGTH, ByteOrder.BIG_ENDIAN);

    assertEquals("Invalid sized checksum for big endian trimmed data", TRIMMED_LENGTH, trimmed.length());
    assertNotSame("Same instance returned for big endian trimmed data", checksum, trimmed);
    assertArrayEquals("Big endian data not trimmed to size", TRIMMED_BIG_ENDIAN, trimmed.getChecksum());
}

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

/**
 * //ww w  .  ja  va  2  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:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpPacketTransport.java

private void init(Settings settings) {
    this.traceEnabled = log.isTraceEnabled();

    this.sendQueueMaxSize = settings.getIntProperty(FFMQCoreSettings.TRANSPORT_TCP_SEND_QUEUE_MAX_SIZE, 1000);
    this.maxPacketSize = client ? -1
            : settings.getIntProperty(FFMQCoreSettings.TRANSPORT_TCP_PACKET_MAX_SIZE, 1024 * 1024 + 1024);

    // Stream buffers
    this.inputBuffer = ByteBuffer.allocate(streamRecvBufferSize).order(ByteOrder.BIG_ENDIAN);
    this.outputBuffer = ByteBuffer.allocate(streamSendBufferSize).order(ByteOrder.BIG_ENDIAN);

    // Packet buffers
    this.packetInputBuffer = new RawDataBuffer(initialPacketBufferSize);
    this.packetOutputBuffer = new RawDataBuffer(initialPacketBufferSize);

    this.lastSendActivity = this.lastRecvActivity = System.currentTimeMillis();
    if (client) {
        sendActivityMonitor = new ActiveObject() {
            /* (non-Javadoc)
             * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#getLastActivity()
             *///from  w  w  w .  j  a  v a  2  s .  c o m
            @Override
            public long getLastActivity() {
                return lastSendActivity;
            }

            /* (non-Javadoc)
             * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#getTimeoutDelay()
             */
            @Override
            public long getTimeoutDelay() {
                return pingInterval * 1000L;
            }

            /* (non-Javadoc)
             * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#onActivityTimeout()
             */
            @Override
            public boolean onActivityTimeout() throws Exception {
                send(new PingQuery());
                return false;
            }
        };
        ActivityWatchdog.getInstance().register(sendActivityMonitor);
    }
    recvActivityMonitor = new ActiveObject() {
        /* (non-Javadoc)
         * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#getLastActivity()
         */
        @Override
        public long getLastActivity() {
            return lastRecvActivity;
        }

        /* (non-Javadoc)
         * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#getTimeoutDelay()
         */
        @Override
        public long getTimeoutDelay() {
            return pingInterval * 1000L * 2;
        }

        /* (non-Javadoc)
         * @see net.timewalker.ffmq4.utils.watchdog.ActiveObject#onActivityTimeout()
         */
        @Override
        public boolean onActivityTimeout() throws Exception {
            log.warn(getId() + " : ping timeout on client socket, closing connection.");
            closeTransport(true);
            return true;
        }
    };
    ActivityWatchdog.getInstance().register(recvActivityMonitor);
}