Java NIO笔记(四):ByteBuffer存取无符号数值

        Java中除了char类型外,其他基本数据类型并没有提供用来处理无符号数值的API,可能有时候需要将无符号的数据转成数据流或文件,可是ByteBuffer并没有提供API来做这样的处理,我们可以自己实现使用ByteBuffer存取无符号数据。

        下面是向ByteBuffer对象中存取无符号数值的工具类:

import java.nio.ByteBuffer;

public class Unsigned {

	public static short getUnsignedByte(ByteBuffer buff) {
		return (short) (buff.get() & 0xff);
	}

	public static short getUnsignedByte(ByteBuffer buff, int position) {
		return (short) (buff.get(position) & (short) 0xff);
	}

	public static void putUnsignedByte(ByteBuffer buff, int value) {
		buff.put((byte) (value & 0xff));
	}

	public static void putUnsignedByte(ByteBuffer buff, int position, int value) {
		buff.put(position, (byte) (value & 0xff));
	}

	// --------------------------------------------
	public static int getUnsignedShort(ByteBuffer buff) {
		return buff.getShort() & 0xffff;
	}

	public static int getUnsignedShort(ByteBuffer buff, int position) {
		return buff.getShort(position) & (short) 0xffff;
	}

	public static void putUnsignedShort(ByteBuffer buff, int value) {
		buff.putShort((short) (value & 0xffff));
	}

	public static void putUnsignedShort(ByteBuffer buff, int position, int value) {
		buff.putShort(position, (short) (value & 0xffff));
	}

	// --------------------------------------------
	public static long getUnsignedInt(ByteBuffer buff) {
		return buff.getInt() & 0xffffffffL;
	}

	public static long getUnsignedInt(ByteBuffer buff, int position) {
		return buff.getInt(position) & 0xffffffffL;
	}

	public static void putUnsignedInt(ByteBuffer buff, int value) {
		buff.putInt((int) (value & 0xffffffffL));
	}

	public static void putUnsignedInt(ByteBuffer buff, int position, int value) {
		buff.putInt(position, (int) (value & 0xffff));
	}

}
        因为Java不提供无符号的byte类型,所以取出来的无符号数值要转成比它大一级的基本数据类型,getUnsignedByte()返回short类型,getUnsignedShort()返回int类型,getUnsignedInt()返回long类型。没有比long更大的基本数据类型,所以不能存取long类型的无符号数值(可以用int替代)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值