Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

In this page you can find the example usage for java.nio ByteBuffer order.

Prototype

Endianness order

To view the source code for java.nio ByteBuffer order.

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

From source file:com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider.java

private short convertTwoBytesToShort(byte[] input, int index) throws SQLServerException {

    short shortVal = -1;
    if (index + 1 >= input.length) {
        throw new SQLServerException(null, SQLServerException.getErrString("R_ByteToShortConversion"), null, 0,
                false);/*from ww  w  .j a va2  s .  c o m*/
    }
    ByteBuffer byteBuffer = ByteBuffer.allocate(2);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.put(input[index]);
    byteBuffer.put(input[index + 1]);
    shortVal = byteBuffer.getShort(0);
    return shortVal;

}

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

/**
 * Parses the ZIP central directory from a byte buffer.
 *
 * @param data/* w w  w .  j  av  a2s  . co 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:com.wolkabout.hexiwear.service.BluetoothService.java

public void setTime() {
    Log.d(TAG, "Setting time...");
    if (!isConnected || alertIn == null) {
        Log.w(TAG, "Time not set.");
        return;//from   w ww .j  a va  2 s.  c  o  m
    }

    final byte[] time = new byte[20];
    final long currentTime = System.currentTimeMillis();
    final long currentTimeWithTimeZoneOffset = (currentTime + TimeZone.getDefault().getOffset(currentTime))
            / 1000;

    final ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().put(currentTimeWithTimeZoneOffset);
    final byte[] utcBytes = buffer.array();

    final byte length = 0x04;

    time[0] = WRITE_TIME;
    time[1] = length;
    time[2] = utcBytes[0];
    time[3] = utcBytes[1];
    time[4] = utcBytes[2];
    time[5] = utcBytes[3];

    alertIn.setValue(time);
    alertIn.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
    bluetoothGatt.writeCharacteristic(alertIn);
}

From source file:ffx.xray.CCP4MapFilter.java

/**
 * {@inheritDoc}//  w w  w  .  j  a va  2 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:guru.benson.pinch.Pinch.java

/**
 * Get a {@link java.net.HttpURLConnection} that has its {@link java.io.InputStream} pointing at
 * the file data of the given {@link guru.benson.pinch.ExtendedZipEntry}.
 *
 * @throws IOException//from   w ww  .  j a  v  a2s .c  om
 */
private HttpURLConnection getEntryInputStream(ExtendedZipEntry entry) throws IOException {
    HttpURLConnection conn;
    InputStream is;

    // Define the local header range
    long start = entry.getOffset();
    long end = start + ZipConstants.LOCHDR;

    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    byte[] dataBuffer = new byte[2048];
    int read, bytes = 0;

    is = conn.getInputStream();
    while ((read = is.read(dataBuffer)) != -1) {
        bytes += read;
    }
    close(is);
    disconnect(conn);
    if (bytes < ZipConstants.LOCHDR) {
        throw new IOException("Unable to fetch the local header");
    }

    ByteBuffer buffer = ByteBuffer.allocate(ZipConstants.LOCHDR);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(dataBuffer, 0, ZipConstants.LOCHDR);

    final int headerSignature = buffer.getInt(0);
    if (headerSignature != 0x04034b50) {
        disconnect(conn);
        throw new IOException("Local file header signature mismatch");
    }

    final int localCompressedSize = buffer.getInt(ZipConstants.LOCSIZ);
    final short localFileNameLength = buffer.getShort(ZipConstants.LOCNAM);
    final short localExtraLength = buffer.getShort(ZipConstants.LOCEXT);

    // Define the local file range
    start = entry.getOffset() + ZipConstants.LOCHDR + localFileNameLength + localExtraLength;
    end = start + localCompressedSize;

    // Open a new one with
    conn = openConnection();
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    conn.setInstanceFollowRedirects(true);
    conn.connect();

    responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
        disconnect(conn);
        close(is);
        throw new IOException("Unexpected HTTP server response: " + responseCode);
    }

    return conn;
}

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).//from w w  w  .j  a v  a2s. co m
 *
 * @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 double[] 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 * data.length);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        fc.read(buffer);
        for (int i = 0; i < data.length; i++) {
            data[i] = buffer.getDouble(8 * i);
        }
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

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).//from   w ww  .  j  av  a2s. c om
 *
 * @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.obm.push.protocol.data.TZDecoder.java

public TimeZone decode(String b64) {
    // Doc : [MS-ASDTYPE] 2.7 TimeZone
    // Doc about types :
    // http://msdn.microsoft.com/fr-fr/library/bb469811.aspx
    // 1 LONG = 4 bytes
    // 1 WCHAR = 2 bytes
    // 1 SYSTEMTIME = 8 SHORT = 8 X 2 bytes
    // TOTAL TIMEZONE STRUCT must be 172 bytes

    byte tzstruct[] = Base64.decodeBase64(b64);

    ByteBuffer bfBias = ByteBuffer.wrap(tzstruct, 0, 4);
    // NOT YET USED
    ///* w ww.j av a 2 s . com*/
    // ByteBuffer bfStandardName = ByteBuffer.wrap(tzstruct, 4, 64);
    // ByteBuffer bfStandardDate = ByteBuffer.wrap(tzstruct, 68, 16);
    // ByteBuffer bfStandardBias = ByteBuffer.wrap(tzstruct, 84, 4);
    // ByteBuffer bfDaylightName = ByteBuffer.wrap(tzstruct, 88, 64);
    // ByteBuffer bfDaylightDate = ByteBuffer.wrap(tzstruct, 152, 16);
    // ByteBuffer bfDaylightBias = ByteBuffer.wrap(tzstruct, 168, 4);

    bfBias.order(ByteOrder.LITTLE_ENDIAN);
    int bias = bfBias.getInt(); // Java integer is 4-bytes-long

    // NOT YET USED
    //
    // bfStandardBias.order(ByteOrder.LITTLE_ENDIAN);
    // int standardBias = bfStandardBias.getInt();
    //      
    // bfDaylightBias.order(ByteOrder.LITTLE_ENDIAN);
    // int daylightBias = bfDaylightBias.getInt();

    TimeZone timezone = TimeZone.getDefault();
    timezone.setRawOffset(bias * 60 * 1000);

    String timezones[] = TimeZone.getAvailableIDs(bias * 60 * 1000);
    if (timezones.length > 0) {
        timezone = TimeZone.getTimeZone(timezones[0]);
    }

    // USEFUL DEBUG LINES
    //
    // StringBuffer sb = new StringBuffer();
    // for (int i = 0; i < 172; i+=1) {
    // sb.append(Byte.valueOf(tzstruct[i]).intValue());
    // }
    //      
    // logger.info("b64: " + b64);
    // logger.info("tzstruct: "+ sb.toString());
    // logger.info("bias: " + bias);
    // logger.info("standardbias: " + standardBias);
    // logger.info("standardname: " +
    // bfStandardName.asCharBuffer().toString());
    // logger.info("daylightBias: " + daylightBias);

    return timezone;
}

From source file:com.nordicsemi.nrfUARTv2.MainActivity.java

private short bytesToShort(byte b1, byte b2) {
    ByteBuffer bb = ByteBuffer.allocate(2);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.put(b1);/* www  .j av  a  2  s.co m*/
    bb.put(b2);
    short shortVal = bb.getShort(0);
    return shortVal;
}

From source file:org.midonet.netlink.rtnetlink.Link.java

@Override
public void use(ByteBuffer buf, short id) {
    ByteOrder originalOrder = buf.order();
    try {/*www  . j  a v a2 s .com*/
        if (!NetlinkMessage.isNested(id)) {
            switch (id) {
            case Attr.IFLA_ADDRESS:
                if (buf.remaining() != 6) {
                    this.mac = null;
                } else {
                    byte[] rhs = new byte[6];
                    buf.get(rhs);
                    this.mac = MAC.fromAddress(rhs);
                }
                break;
            case Attr.IFLA_IFNAME:
                byte[] s = new byte[buf.remaining() - 1];
                buf.get(s);
                this.ifname = new String(s);
                break;
            case Attr.IFLA_MASTER:
                if (buf.remaining() == 4) {
                    this.masterIndex = buf.getInt();
                }
                break;
            case Attr.IFLA_MTU:
                if (buf.remaining() != 4) {
                    this.mtu = 0;
                } else {
                    this.mtu = buf.getInt();
                }
                break;
            case Attr.IFLA_LINK:
                if (buf.remaining() != 4) {
                    this.link = this.ifi.index;
                } else {
                    this.link = buf.getInt();
                }
                break;
            case Attr.IFLA_LINKINFO:
                NetlinkMessage.scanNestedAttribute(buf, this);
                break;
            default:
                break;
            }
        } else {
            switch (NetlinkMessage.unnest(id)) {
            case NestedAttr.LinkInfo.IFLA_INFO_KIND:
                byte[] s = new byte[buf.remaining() - 1];
                buf.get(s);
                // Since the longest length for the field is 7, netlink
                // assigns 7 bytes here, by padding with '0's to the
                // right
                int zeroIdx = ArrayUtils.indexOf(s, (byte) 0);
                if (zeroIdx == ArrayUtils.INDEX_NOT_FOUND) {
                    info.kind = new String(s);
                } else {
                    info.kind = new String(Arrays.copyOf(s, zeroIdx));
                }
                break;
            case NestedAttr.LinkInfo.IFLA_INFO_DATA:
                byte[] data = new byte[buf.remaining() - 1];
                buf.get(data);
                info.data = ByteBuffer.wrap(data);
                break;
            default:
                break;
            }
        }
    } finally {
        buf.order(originalOrder);
    }
}