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.woodcomputing.bobbin.format.PESFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);//w  ww. j a  va2  s  . c  o m
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    Design design = new Design();
    log.debug("Magic: {}{}{}{}", (char) bb.get(), (char) bb.get(), (char) bb.get(), (char) bb.get());
    int pecStart = bb.getInt(8);
    log.debug("PEC Start: {}", pecStart);
    byte colorCount = bb.get(pecStart + 48);
    log.debug("Color Count: {}", colorCount);
    int colors[] = new int[colorCount];
    for (int i = 0; i < colorCount; i++) {
        colors[i] = bb.get() & 0xFF;
        log.debug("Color[{}] = {}", i, colors[i]);
    }

    bb.position(pecStart + 532);
    int x;
    int y;
    int colorChanges = 0;
    PESColor color = pesColorMap.get(colors[colorChanges++]);
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getColor());

    while (true) {
        x = bb.get() & 0xFF;
        y = bb.get() & 0xFF;
        if (x == 0xFF && y == 0x00) {
            log.debug("End of stitches");
            break;
        }
        if (x == 0xFE && y == 0xB0) {
            int colorIndex = bb.get() & 0xFF;
            log.debug("Color change: {}", colorIndex);
            color = pesColorMap.get(colors[colorChanges++]);
            stitchGroup = new StitchGroup();
            stitchGroup.setColor(color.getColor());
            continue;
        }
        if ((x & 0x80) > 0) {
            log.debug("Testing X: {} -  X & 0x80: {}", x, x & 0x80);
            if ((x & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((x & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            x = ((x & 0x0F) << 8) + y;

            if ((x & 0x800) > 0) {
                x -= 0x1000;
            }
            y = bb.get() & 0xFF;

        } else if (x >= 0x40) {
            x -= 0x80;
        }
        if ((y & 0x80) > 0) {
            log.debug("Testing Y: {} -  Y & 0x80: {}", y, y & 0x80);
            if ((y & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((y & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            y = ((y & 0x0F) << 8) + bb.get() & 0xFF;

            if ((y & 0x800) > 0) {
                y -= 0x1000;
            }
        } else if (y >= 0x40) {
            y -= 0x80;
        }
        //            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
        //            stitchGroup.getStitches().add(designStitch);
        log.debug("X: {} Y: {}", x, y);
    }
    log.debug("Color Changes: {}", colorChanges);
    return design;
}

From source file:cfa.vo.interop.EncodeDoubleArray.java

public static String encodeBase64(double[] data, boolean swapByteOrder) throws IOException {

    byte[] decodedData = doubleToByte(data);

    if (swapByteOrder) {
        ByteBuffer buf = ByteBuffer.wrap(decodedData);
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.get(decodedData);//  w  w w.  j  a  v  a 2s.  co  m
    }

    Base64 codec = new Base64();
    byte[] encodedData = codec.encode(decodedData);

    String result = new String(encodedData);

    return result;
}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PUSH_DATA);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 8) {
        throw new MalformedPacketException("too short");
    }/*from   w  ww  . j a v a  2 s .  c om*/

    gatewayEui = new byte[8];
    _raw.get(gatewayEui);

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    stats = new ArrayList<>();
    rxpks = new ArrayList<>();

    if (jo.has("rxpk")) {
        if (!jo.get("rxpk").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (rxpk)");
        }
        JSONArray rxpk = jo.getJSONArray("rxpk");

        for (int i = 0; i < rxpk.length(); i++) {
            rxpks.add(new Rxpk(rxpk.getJSONObject(i)));
        }
    }

    if (jo.has("stat")) {
        if (!jo.get("stat").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (stat)");
        }
        JSONArray stat = jo.getJSONArray("stat");

        for (int i = 0; i < stat.length(); i++) {
            stats.add(new Stat(stat.getJSONObject(i)));
        }
    }

}

From source file:Main.java

public static String largeFileSha1(File file) {
    InputStream inputStream = null;
    try {/*from   ww  w.  j  av  a2  s. c  o m*/
        MessageDigest gsha1 = MessageDigest.getInstance("SHA1");
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        inputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[1024];
        int nRead = 0;
        int block = 0;
        int count = 0;
        final int BLOCK_SIZE = 4 * 1024 * 1024;
        while ((nRead = inputStream.read(buffer)) != -1) {
            count += nRead;
            sha1.update(buffer, 0, nRead);
            if (BLOCK_SIZE == count) {
                gsha1.update(sha1.digest());
                sha1 = MessageDigest.getInstance("SHA1");
                block++;
                count = 0;
            }
        }
        if (count != 0) {
            gsha1.update(sha1.digest());
            block++;
        }
        byte[] digest = gsha1.digest();

        byte[] blockBytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(block).array();

        byte[] result = ByteBuffer.allocate(4 + digest.length).put(blockBytes, 0, blockBytes.length)
                .put(digest, 0, digest.length).array();

        return Base64.encodeToString(result, Base64.URL_SAFE | Base64.NO_WRAP);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:org.apache.tajo.tuple.memory.ResizableMemoryBlock.java

public ResizableMemoryBlock(ByteBuf buffer, ResizableLimitSpec limitSpec) {
    this.buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
    this.limitSpec = limitSpec;
    this.memoryAddress = this.buffer.hasMemoryAddress() ? this.buffer.memoryAddress() : 0;
}

From source file:com.woodcomputing.bobbin.format.JEFFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);//from   www .j a va2s .co m
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    JEF jef = new JEF();
    jef.setFirstStitchLocation(bb.getInt(0));
    log.debug("First Stitch Location: {}", jef.getFirstStitchLocation());
    jef.setThreadChangeCount(bb.getInt(24));
    log.debug("Threads Changes: {}", jef.getThreadChangeCount());
    jef.setHoop(Hoop.id2Hoop(bb.getInt(32)));
    log.debug("Hoop: {}", jef.getHoop());
    jef.setStitchCount(bb.getInt(28));
    log.debug("Stitch Count: {}", jef.getStitchCount());

    bb.position(116);
    JEFColor[] colors = new JEFColor[jef.getThreadChangeCount()];
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        colors[i] = jefColorMap.get(bb.getInt());
    }
    jef.setThreadColors(colors);
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        log.debug("ThreadType{}: {}", i, bb.getInt());
    }

    int dx = 0;
    int dy = 0;
    int cx = 0;
    int cy = 0;
    int nx = 0;
    int ny = 0;

    int change = 1;
    int stitches = 0;
    boolean isMove = false;
    bb.position(jef.getFirstStitchLocation());
    JEFColor color = jef.getThreadColors()[change - 1];
    Design design = new Design();
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getRgb());

    for (int stitch = 1; stitch < jef.getStitchCount(); stitch++) {
        dx = bb.get();
        dy = bb.get();
        if (dx == -128) {
            switch (dy) {
            case 1:
                log.debug("change: {}", bb.position());
                change++;
                color = jef.getThreadColors()[change - 1];
                design.getStitchGroups().add(stitchGroup);
                stitchGroup = new StitchGroup();
                stitchGroup.setColor(color.getRgb());
                //                        bb.get();
                //                        bb.get();
                continue;
            case 2:
                //                        log.debug("move");
                isMove = true;
                break;
            case 16:
                log.debug("last");
                isMove = true;
                break;
            }
        } else {
            nx = cx + dx;
            ny = cy + dy;
            if (isMove) {
                isMove = false;
            }
            //                } else {
            //                    log.debug("stitch");
            stitches++;
            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
            stitchGroup.getStitches().add(designStitch);
            //                }
            cx = nx;
            cy = ny;
        }
    }
    log.debug("Changes: {} Stitches {} End: {}", change, stitches, bb.position());
    return design;
}

From source file:org.openhab.binding.ulux.internal.ump.messages.AbstractUluxMessage.java

@Override
public final ByteBuffer getBuffer() {
    final ByteBuffer buffer = ByteBuffer.wrap(new byte[this.length]);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.put(this.length);
    buffer.put(this.messageId.toByte());
    buffer.putShort(this.actorId);

    addData(buffer);// w ww. j a  v  a 2s.c o m

    buffer.flip();

    return buffer;
}

From source file:StreamUtility.java

/**
 * Converts little endian bytes to a long
 * @param value byte array to read//www  . j  ava 2  s . co m
 * @return long value of the byte array
 */
public static long littleEndianToLong(byte[] value) {
    return ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).getLong();
}

From source file:Main.java

public static long getCommentLength(final FileChannel fileChannel) throws IOException {
    // End of central directory record (EOCD)
    // Offset    Bytes     Description[23]
    // 0           4       End of central directory signature = 0x06054b50
    // 4           2       Number of this disk
    // 6           2       Disk where central directory starts
    // 8           2       Number of central directory records on this disk
    // 10          2       Total number of central directory records
    // 12          4       Size of central directory (bytes)
    // 16          4       Offset of start of central directory, relative to start of archive
    // 20          2       Comment length (n)
    // 22          n       Comment
    // For a zip with no archive comment, the
    // end-of-central-directory record will be 22 bytes long, so
    // we expect to find the EOCD marker 22 bytes from the end.

    final long archiveSize = fileChannel.size();
    if (archiveSize < ZIP_EOCD_REC_MIN_SIZE) {
        throw new IOException("APK too small for ZIP End of Central Directory (EOCD) record");
    }//from w  w w  .  ja  va  2s .com
    // ZIP End of Central Directory (EOCD) record is located at the very end of the ZIP archive.
    // The record can be identified by its 4-byte signature/magic which is located at the very
    // beginning of the record. A complication is that the record is variable-length because of
    // the comment field.
    // The algorithm for locating the ZIP EOCD record is as follows. We search backwards from
    // end of the buffer for the EOCD record signature. Whenever we find a signature, we check
    // the candidate record's comment length is such that the remainder of the record takes up
    // exactly the remaining bytes in the buffer. The search is bounded because the maximum
    // size of the comment field is 65535 bytes because the field is an unsigned 16-bit number.
    final long maxCommentLength = Math.min(archiveSize - ZIP_EOCD_REC_MIN_SIZE, UINT16_MAX_VALUE);
    final long eocdWithEmptyCommentStartPosition = archiveSize - ZIP_EOCD_REC_MIN_SIZE;
    for (int expectedCommentLength = 0; expectedCommentLength <= maxCommentLength; expectedCommentLength++) {
        final long eocdStartPos = eocdWithEmptyCommentStartPosition - expectedCommentLength;

        final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        fileChannel.position(eocdStartPos);
        fileChannel.read(byteBuffer);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);

        if (byteBuffer.getInt(0) == ZIP_EOCD_REC_SIG) {
            final ByteBuffer commentLengthByteBuffer = ByteBuffer.allocate(2);
            fileChannel.position(eocdStartPos + ZIP_EOCD_COMMENT_LENGTH_FIELD_OFFSET);
            fileChannel.read(commentLengthByteBuffer);
            commentLengthByteBuffer.order(ByteOrder.LITTLE_ENDIAN);

            final int actualCommentLength = commentLengthByteBuffer.getShort(0);
            if (actualCommentLength == expectedCommentLength) {
                return actualCommentLength;
            }
        }
    }
    throw new IOException("ZIP End of Central Directory (EOCD) record not found");
}

From source file:io.druid.segment.data.CompressedColumnarIntsSerializerTest.java

@Parameterized.Parameters(name = "{index}: compression={0}, byteOrder={1}")
public static Iterable<Object[]> compressionStrategiesAndByteOrders() {
    Set<List<Object>> combinations = Sets.cartesianProduct(Sets.newHashSet(CompressionStrategy.noNoneValues()),
            Sets.newHashSet(ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN));

    return Iterables.transform(combinations, new Function<List, Object[]>() {
        @Override/*  ww w. j  a  va  2s  .  c  o m*/
        public Object[] apply(List input) {
            return new Object[] { input.get(0), input.get(1) };
        }
    });
}