java bytebuffer

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class bytebuffertest {

	public static void main(String[] args)
	{
		// Create a ByteBuffer using a byte array
		byte[] bytes = new byte[10];
		ByteBuffer buf = ByteBuffer.wrap(bytes);

		// Create a non-direct ByteBuffer with a 10 byte capacity
		// The underlying storage is a byte array.
		buf = ByteBuffer.allocate(10);

		// Create a direct (memory-mapped) ByteBuffer with a 10 byte capacity.
		buf = ByteBuffer.allocateDirect(10);

		
		// Create an empty ByteBuffer with a 10 byte capacity
		ByteBuffer bbuf = ByteBuffer.allocate(10);

		// Get the ByteBuffer's capacity
		int capacity = bbuf.capacity(); // 10
		System.out.println(capacity);

		// Use the absolute get().
		// This method does not affect the position.
		byte b = bbuf.get(5); // position=0

		// Set the position
		bbuf.position(5);

		// Use the relative get()
		b = bbuf.get();

		// Get the new position
		int pos = bbuf.position(); // 6

		// Get remaining byte count
		int rem = bbuf.remaining(); // 4

		// Set the limit
		bbuf.limit(7); // remaining=1

		// This convenience method sets the position to 0
		bbuf.rewind(); // remaining=7
		
		//Converting Between a ByteBuffer an a Byte Array 

		// Create a ByteBuffer from a byte array
		byte[] bytes1 = new byte[10];
		ByteBuffer buf1 = ByteBuffer.wrap(bytes);

		// Retrieve bytes between the position and limit
		// (see Putting Bytes into a ByteBuffer)
		bytes1 = new byte[buf.remaining()];
		buf1.get(bytes1, 0, bytes1.length);

		// Retrieve all bytes in the buffer
		buf1.clear();
		bytes1 = new byte[buf1.capacity()];
		buf1.get(bytes1, 0, bytes1.length);
		
		// Use the absolute put().
		// This method does not affect the position.
		bbuf.put((byte)0xFF); // position=0

		// Set the position
		bbuf.position(5);

		// Use the relative put()
		bbuf.put((byte)0xFF);

		// Get the new position
		int pos1 = bbuf.position(); // 6
		
		
		//Setting the Byte Ordering for a ByteBuffer 
		// Get default byte ordering
		ByteOrder order = buf.order(); // ByteOrder.BIG_ENDIAN

		// Put a multibyte value
		buf.putShort(0, (short)123);
		buf.get(0); // 0
		buf.get(1); // 123

		// Set to little endian
		buf.order(ByteOrder.LITTLE_ENDIAN);

		// Put a multibyte value
		buf.putShort(0, (short)123);
		buf.get(0); // 123
		buf.get(1); // 0



	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值