无符号转Java有符号

用Java解析二进制文件,一般会碰到文件中含有无符号格式的数字,而Java的基本数据类型只支持有符号类型。

转换方法:


1.按byte读取

2.将byte数组转换成相应的Java基本类型。一般情况下,UNIT16转换成int,UNIT8转换成short,UNIT32转换成long。

  下面仅举例UNIT16转换成int,其中,为了防止输入的byte数组长度,不是2,做了保护。(超过4的字节的处理),如果会造成性能问题,同时保证不会传入超过4个字节的参数,可以不保护。


public class Main {

	// 将2个字节转换成int
	private static int toInt(byte[] bytes) {
		int ret = ((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff);
		return ret;
	}

	// 将2个网络字节序字节转换成int
	private static int toRInt(byte[] bytes) {
		int ret = ((bytes[1] & 0xff) << 8) | (bytes[0] & 0xff);
		return ret;
	}

	// 将size个字节转换成int,其中如果size〉4,取后四位
	private static int toInt(byte[] bytes, int size) {
		int ret = 0;
		int beginPos = size > 4 ? size - 4 : 0;
		for (int i = beginPos; i < size; ++i) {
			ret = (ret << 8) | (bytes[i] & 0xff);
		}
		return ret;
	}

	// 将size个网络字节序字节转换成int,其中如果size〉4,取前四位
	private static int toRInt(byte[] bytes, int size) {
		int ret = 0;
		int beginPos = size > 4 ? 4 : size;
		for (int i = beginPos - 1; i >= 0; --i) {
			ret = (ret << 8) | (bytes[i] & 0xff);
		}
		return ret;
	}

	public static void main(String[] args) {

		byte[] b2 = new byte[] { -1, -1 };

		int n1 = toInt(b2, 2);
		int n2 = toRInt(b2, 2);

		int n11 = toInt(b2);
		int n22 = toRInt(b2);

		byte[] b3 = new byte[] { 10, 0 };
		int n3 = toInt(b3, 2);
		int n4 = toRInt(b3, 2);
		short s = (short) n3;
		int n5 = Short.reverseBytes(s);

		int n33 = toInt(b3);
		int n44 = toRInt(b3);

		int n6 = toInt((short) -1);
		int n7 = toRInt((short) -1);

		int n8 = toInt((short) n3);
		int n9 = toRInt((short) n4);

	}

	private static int toInt(short shortVal) {
		int ret = shortVal > 0 ? shortVal : (shortVal & 0xffff);
		return ret;
	}

	private static int toRInt(short shortVal) {
		shortVal = Short.reverseBytes(shortVal);
		int ret = shortVal > 0 ? shortVal : (shortVal & 0xffff);
		return ret;
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值