Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:Main.java

/**
 * Finds the percentage of pixels that do are empty.
 *
 * @param bitmap input bitmap/*from   w  w  w. j  a v  a 2  s  . co  m*/
 * @return a value between 0.0 to 1.0 . Note the method will return 0.0 if either of bitmaps are null nor of same size.
 *
 */
public static float getTransparentPixelPercent(Bitmap bitmap) {

    if (bitmap == null) {
        return 0f;
    }

    ByteBuffer buffer = ByteBuffer.allocate(bitmap.getHeight() * bitmap.getRowBytes());
    bitmap.copyPixelsToBuffer(buffer);

    byte[] array = buffer.array();

    int len = array.length;
    int count = 0;

    for (int i = 0; i < len; i++) {
        if (array[i] == 0) {
            count++;
        }
    }

    return ((float) (count)) / len;
}

From source file:Main.java

public static byte[] aesIGEdecrypt(byte[] tmpAESiv, byte[] tmpAesKey, byte[] data) {
    try {//w w  w  . j  a va  2s .  c o m

        ByteBuffer out = ByteBuffer.allocate(data.length);

        byte[] iv2p = Arrays.copyOfRange(tmpAESiv, 0, tmpAESiv.length / 2);
        byte[] ivp = Arrays.copyOfRange(tmpAESiv, tmpAESiv.length / 2, tmpAESiv.length);

        int len = data.length / AES_BLOCK_SIZE;

        byte[] xorInput = null;
        byte[] xorOutput = null;

        SecretKeySpec keySpec = null;
        keySpec = new SecretKeySpec(tmpAesKey, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        byte[] input = null;
        byte[] output = null;

        for (int i = 0; i < len; i++) {
            input = Arrays.copyOfRange(data, i * AES_BLOCK_SIZE, (i + 1) * AES_BLOCK_SIZE);
            xorInput = xor(input, ivp);
            output = cipher.doFinal(xorInput);
            xorOutput = xor(output, iv2p);
            out.put(xorOutput);

            ivp = xorOutput;
            iv2p = input;
        }
        return out.array();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static String readString(String filePath) {
    File file = new File(filePath);
    if (!file.exists())
        return null;

    FileInputStream fileInput = null;
    FileChannel channel = null;//from w w  w .  j  a va2s . c  o m
    try {
        fileInput = new FileInputStream(filePath);
        channel = fileInput.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
        channel.read(buffer);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byteArrayOutputStream.write(buffer.array());
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
    } finally {

        if (fileInput != null) {
            try {
                fileInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:MainClass.java

private static void test() throws Exception {
    long[] primes = new long[] { 1, 2, 3, 5, 7 };
    File aFile = new File("C:/test/primes.txt");
    FileOutputStream outputFile = null;
    outputFile = new FileOutputStream(aFile);
    FileChannel file = outputFile.getChannel();
    ByteBuffer[] buffers = new ByteBuffer[3];
    buffers[0] = ByteBuffer.allocate(8);
    buffers[2] = ByteBuffer.allocate(8);
    String primeStr = null;//from ww  w. j  ava2  s  . c o  m
    for (long prime : primes) {
        primeStr = "prime = " + prime;
        buffers[0].putDouble((double) primeStr.length()).flip();
        buffers[1] = ByteBuffer.allocate(primeStr.length());
        buffers[1].put(primeStr.getBytes()).flip();
        buffers[2].putLong(prime).flip();
        file.write(buffers);
        buffers[0].clear();
        buffers[2].clear();
    }
    System.out.println("File written is " + file.size() + "bytes.");
    outputFile.close();
}

From source file:Main.java

public static BigInteger getZ(ArrayList<byte[]> c1, ArrayList<byte[]> c2, BigInteger p) {
    BigInteger z = BigInteger.ZERO;

    //TODO: make sure c1 and c2 are of the same size
    int size = c1.size();
    if (size > c2.size()) {
        size = c2.size();//from www.  jav a2s.c om
    }

    for (int i = 0; i < size; i++) {
        BigInteger c1BI = new BigInteger(1, c1.get(i));
        BigInteger c2BI = new BigInteger(1, c2.get(i));
        BigInteger exp = new BigInteger(1, ByteBuffer.allocate(8).putLong((long) Math.pow(2, i)).array());

        z = z.add((c1BI.multiply(c2BI)).modPow(exp, p));
        Log.d("CeCk", "z calculation " + i + "/" + size + " round");
    }
    return z.mod(p);
}

From source file:Main.java

/**
 * Combine messages in an array and put a size header before each message
 * @param array/*from  w w  w .j  a v a  2  s  .  co  m*/
 * @return
 */
public static byte[] compileMessages(ArrayList<byte[]> array) {

    int bufferSize = 0;
    for (int i = 0; i < array.size(); i++) {
        byte[] thisByte = array.get(i);
        bufferSize += (4 + thisByte.length);
    }

    byte[] buffer = new byte[bufferSize];

    int pointer = 0; // used to index the next empty byte to fill
    for (int i = 0; i < array.size(); i++) {
        int thisSize = array.get(i).length;
        System.arraycopy(ByteBuffer.allocate(4).putInt(thisSize).array(), 0, buffer, pointer, 4);
        System.arraycopy(array.get(i), 0, buffer, pointer + 4, thisSize);
        pointer += (4 + thisSize);
    }

    return buffer;
}

From source file:Main.java

/**
 * Convert from singed 16-bit PCM to 32-bit float PCM.
 * @param byteArray byte array/* w ww  .j  av  a2  s  .  co m*/
 * @return byte array
 */
public static byte[] convert16BitTo32Bit(final byte[] byteArray) {
    float[] audioDataF = shortToFloat(byteToShort(byteArray));
    for (int i = 0; i < audioDataF.length; i++) {
        audioDataF[i] /= 32768.0;
    }

    FloatBuffer fb = FloatBuffer.wrap(audioDataF);
    ByteBuffer byteBuffer = ByteBuffer.allocate(fb.capacity() * 4);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.asFloatBuffer().put(fb);
    return byteBuffer.array();
}

From source file:Main.java

/**
 * Compares two bitmaps and gives the percentage of similarity
 *
 * @param bitmap1 input bitmap 1//w w  w  .j av a2 s . com
 * @param bitmap2 input bitmap 2
 * @return a value between 0.0 to 1.0 . Note the method will return 0.0 if either of bitmaps are null nor of same size.
 *
 */
public static float compareEquivalance(Bitmap bitmap1, Bitmap bitmap2) {

    if (bitmap1 == null || bitmap2 == null || bitmap1.getWidth() != bitmap2.getWidth()
            || bitmap1.getHeight() != bitmap2.getHeight()) {
        return 0f;
    }

    ByteBuffer buffer1 = ByteBuffer.allocate(bitmap1.getHeight() * bitmap1.getRowBytes());
    bitmap1.copyPixelsToBuffer(buffer1);

    ByteBuffer buffer2 = ByteBuffer.allocate(bitmap2.getHeight() * bitmap2.getRowBytes());
    bitmap2.copyPixelsToBuffer(buffer2);

    byte[] array1 = buffer1.array();
    byte[] array2 = buffer2.array();

    int len = array1.length; // array1 and array2 will be of some length.
    int count = 0;

    for (int i = 0; i < len; i++) {
        if (array1[i] == array2[i]) {
            count++;
        }
    }

    return ((float) (count)) / len;
}

From source file:IOUtilities.java

/**
 * Copy ALL available data from one stream into another
 * @param in//from w ww. j  av  a2 s  . co  m
 * @param out
 * @throws IOException
 */
public static void copy(InputStream in, OutputStream out) throws IOException {
    ReadableByteChannel source = Channels.newChannel(in);
    WritableByteChannel target = Channels.newChannel(out);

    ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
    while (source.read(buffer) != -1) {
        buffer.flip(); // Prepare the buffer to be drained
        while (buffer.hasRemaining()) {
            target.write(buffer);
        }
        buffer.clear(); // Empty buffer to get ready for filling
    }

    source.close();
    target.close();

}

From source file:Main.java

/**
 * Return a BCD representation of an integer as a 4-byte array.
 * @param i int//from w ww. j a  va  2  s . com
 * @return  byte[4]
 */
public static byte[] intToBcdArray(int i) {
    if (i < 0)
        throw new IllegalArgumentException("Argument cannot be a negative integer.");

    StringBuilder binaryString = new StringBuilder();

    while (true) {
        int quotient = i / 10;
        int remainder = i % 10;
        String nibble = String.format("%4s", Integer.toBinaryString(remainder)).replace(' ', '0');
        binaryString.insert(0, nibble);

        if (quotient == 0) {
            break;
        } else {
            i = quotient;
        }
    }

    return ByteBuffer.allocate(4).putInt(Integer.parseInt(binaryString.toString(), 2)).array();
}