Sunday 16 June 2019

NIO: Convert ByteBuffer to IntBuffer


ByteBuffer provides asIntBuffer method to convert ByteBuffer to IntBuffer.

Example
IntBuffer intBuffer = byteBuffer.asIntBuffer();

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class Test {

 public static void main(String... args) throws IOException {

  ByteBuffer byteBuffer = ByteBuffer.allocate(100);

  byteBuffer.putInt(10);
  byteBuffer.putInt(20);
  byteBuffer.putInt(30);
  byteBuffer.putInt(40);

  byteBuffer.flip();

  IntBuffer intBuffer = byteBuffer.asIntBuffer();

  for (int i = 0; i < intBuffer.limit(); i++) {
   System.out.println("Element at index " + i + " is " + intBuffer.get(i));
  }

 }
}

Output
Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40



Previous                                                 Next                                                 Home

No comments:

Post a Comment