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:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *///  ww w .  ja  v a 2s. c om
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}

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();/*from  w  w w. j a v  a  2s .co m*/
}

From source file:org.geowebcache.arcgis.compact.ArcGISCompactCache.java

/**
 * Read from a file that uses little endian byte order.
 *
 * @param filePath Path to file/*  w ww . ja v a  2s  .  c o  m*/
 * @param offset Read at offset
 * @param length Read length bytes
 * @return ByteBuffer that contains read bytes and has byte order set to little endian. The
 *     length of the byte buffer is multiple of 4, so getInt() and getLong() can be used even
 *     when fewer bytes are read.
 */
protected ByteBuffer readFromLittleEndianFile(String filePath, long offset, int length) {
    ByteBuffer result = null;

    try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
        file.seek(offset);
        // pad to multiples of 4 so we can use getInt() and getLong()
        int padding = 4 - (length % 4);
        byte data[] = new byte[length + padding];

        if (file.read(data, 0, length) != length)
            throw new IOException("not enough bytes read or reached end of file");

        result = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
    } catch (IOException e) {
        logger.warn("Failed to read from little endian file", e);
    }

    return result;
}

From source file:au.org.ala.delta.translation.dist.DistItemsFileWriter.java

protected Pair<List<Integer>, List<Integer>> writeItems(int[] wordOffsets, int[] bitOffsets) {
    final int BYTES_IN_WORD = 4;
    List<Integer> itemRecords = new ArrayList<Integer>();
    List<Integer> nameLengths = new ArrayList<Integer>();
    int size = BinaryKeyFile.RECORD_LENGTH_BYTES;
    for (int offset : wordOffsets) {
        size = Math.max(size, offset);
    }//ww  w. jav a 2 s.co  m
    Iterator<Item> items = _dataSet.unfilteredItems();
    while (items.hasNext()) {
        Item item = items.next();
        String description = _itemFormatter.formatItemDescription(item);
        nameLengths.add(description.length());
        byte[] bytes = new byte[(size + 1) * BYTES_IN_WORD];
        Arrays.fill(bytes, (byte) 0);

        ByteBuffer work = ByteBuffer.wrap(bytes);
        work.order(ByteOrder.LITTLE_ENDIAN);

        Iterator<IdentificationKeyCharacter> chars = _dataSet.unfilteredIdentificationKeyCharacterIterator();
        while (chars.hasNext()) {
            IdentificationKeyCharacter keyChar = chars.next();
            int charNum = keyChar.getCharacterNumber();
            if (!keyChar.getCharacterType().isText()) {
                int offset = wordOffsets[keyChar.getCharacterNumber() - 1] - 1;
                if (!(keyChar.getCharacterType() == CharacterType.UnorderedMultiState)) {
                    work.putFloat(offset * BYTES_IN_WORD, -9999.0f);
                }
                Attribute attribute = item.getAttribute(keyChar.getCharacter());
                if (attribute == null || attribute.isUnknown()) {
                    continue;
                }
                switch (keyChar.getCharacterType()) {
                case UnorderedMultiState:
                    encodeUnorderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1,
                            bitOffsets[charNum - 1], keyChar, (MultiStateAttribute) attribute);

                    break;
                case OrderedMultiState:
                    encodeOrderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1, keyChar,
                            (MultiStateAttribute) attribute);
                    break;
                case IntegerNumeric:
                case RealNumeric:
                    encodeNumericAttribute(work, wordOffsets[charNum - 1] - 1, keyChar,
                            (NumericAttribute) attribute);

                    break;
                }
            }

        }
        itemRecords.add(_itemsFile.writeItem(description, work));
    }
    return new Pair<List<Integer>, List<Integer>>(itemRecords, nameLengths);
}

From source file:org.lic.ip.ipseeker.IPSeeker.java

/**
 * ?//from  w  w w  .  j  av a 2  s.  c  om
 */
private IPSeeker() {
    tmpBuf = new byte[100];
    tmpB4 = new byte[4];

    try {
        String filepath = getClass().getClassLoader().getResource("qqwry.dat").getPath();
        ipFile = new RandomAccessFile(filepath, "r");
        // ipFile = new RandomAccessFile(ClassLoader.getSystemResource(
        // ip_filename).getPath(), "r");
    } catch (IOException e) {
        logger.error("IP??IP");
        return;
    }

    if (ipFile == null)
        return;

    // ??
    try {
        ipBegin = readInt4(0);
        ipEnd = readInt4(4);
        if (ipBegin == -1 || ipEnd == -1) {
            ipFile.close();
            ipFile = null;
            return;
        }
    } catch (IOException e) {
        logger.error("IP???IP");
        ipFile = null;
        return;
    }

    // IP?
    try {
        FileChannel fc = ipFile.getChannel();
        long ipFileLen = ipFile.length();
        mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFileLen);
        mbb.order(ByteOrder.LITTLE_ENDIAN);
        ipFile.close();

        logger.info("read ip file to memory, len = " + ipFileLen + " bytes");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.htrace.impl.PackedBuffer.java

/**
 * Write the fixed-length request frame which starts packed RPC messages.
 *//*  ww  w.  j a v a 2 s .co  m*/
static void writeReqFrame(ByteBuffer bb, int methodId, long seq, int length) throws IOException {
    int oldPos = bb.position();
    boolean success = false;
    try {
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(HRPC_MAGIC);
        bb.putInt(methodId);
        bb.putLong(seq);
        bb.putInt(length);
        success = true;
    } finally {
        if (!success) {
            bb.position(oldPos);
        }
    }
}

From source file:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}//from www  .  j a va  2s . co  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}// ww w.  j a  va  2 s .co m
 */
@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.mcisb.util.math.MathUtils.java

/**
 * /*from w  w w . j a  v  a 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:ru.jts_dev.gameserver.config.GameIntegrationConfig.java

/**
 * Ingoing message flow//from  w w w .j a  v  a  2  s .c om
 *
 * @return - complete message transformation flow
 */
@Bean
public IntegrationFlow recvFlow() {
    return IntegrationFlows.from(tcpInputChannel())
            .transform(byte[].class, b -> wrappedBuffer(b).order(ByteOrder.LITTLE_ENDIAN))
            // no crypt for RequestProtocolVersion
            .route(ByteBuf.class, b -> b.readableBytes() > 0 && b.getByte(0) == 0x0E,
                    invoker -> invoker.subFlowMapping("true", sf -> sf.transform(b -> b))
                            .subFlowMapping("false", sf -> sf.transform(encoder, "decrypt")))
            .transform(clientPacketHandler, "handle").channel(incomingPacketExecutorChannel()).get();
}