java中int与byte,以及long与byte之间的转换

转载请注明出处!

原文链接:http://blog.csdn.net/zgyulongfei/article/details/7738970


做项目时候根据协议在发送网络流的时候需要将所有int及long转换成byte,因此写了以下的转换方法,希望能帮助到需要的朋友 ^_^

闲话少说,直接上码。

public class Utilities {
	public static byte[] int2Bytes(int num) {
		byte[] byteNum = new byte[4];
		for (int ix = 0; ix < 4; ++ix) {
			int offset = 32 - (ix + 1) * 8;
			byteNum[ix] = (byte) ((num >> offset) & 0xff);
		}
		return byteNum;
	}

	public static int bytes2Int(byte[] byteNum) {
		int num = 0;
		for (int ix = 0; ix < 4; ++ix) {
			num <<= 8;
			num |= (byteNum[ix] & 0xff);
		}
		return num;
	}

	public static byte int2OneByte(int num) {
		return (byte) (num & 0x000000ff);
	}

	public static int oneByte2Int(byte byteNum) {
                //针对正数的int
		return byteNum > 0 ? byteNum : (128 + (128 + byteNum));
	}

	public static byte[] long2Bytes(long num) {
		byte[] byteNum = new byte[8];
		for (int ix = 0; ix < 8; ++ix) {
			int offset = 64 - (ix + 1) * 8;
			byteNum[ix] = (byte) ((num >> offset) & 0xff);
		}
		return byteNum;
	}

	public static long bytes2Long(byte[] byteNum) {
		long num = 0;
		for (int ix = 0; ix < 8; ++ix) {
			num <<= 8;
			num |= (byteNum[ix] & 0xff);
		}
		return num;
	}
}

public class TestMain {
	public static void main(String[] args) {
		int num = 129;
		System.out.println("测试的int值为:" + num);

		byte[] int2bytes = Utilities.int2Bytes(num);
		System.out.printf("int转成bytes: ");
		for (int i = 0; i < 4; ++i) {
			System.out.print(int2bytes[i] + " ");
		}
		System.out.println();

		int bytes2int = Utilities.bytes2Int(int2bytes);
		System.out.println("bytes转行成int: " + bytes2int);

		byte int2OneByte = Utilities.int2OneByte(num);
		System.out.println("int转行成one byte: " + int2OneByte);

		int oneByte2Int = Utilities.oneByte2Int(int2OneByte);
		System.out.println("one byte转行成int: " + oneByte2Int);
		System.out.println();

		long longNum = 100000;
		System.out.println("测试的long值为:" + longNum);

		byte[] long2Bytes = Utilities.long2Bytes(longNum);
		System.out.printf("long转行成bytes: ");
		for (int ix = 0; ix < long2Bytes.length; ++ix) {
			System.out.print(long2Bytes[ix] + " ");
		}
		System.out.println();

		long bytes2Long = Utilities.bytes2Long(long2Bytes);
		System.out.println("bytes转行成long: " + bytes2Long);
	}
}

测试结果如下:

测试的int值为:156
int转成bytes: 0 0 0 -100 
bytes转行成int: 156
int转行成one byte: -100
one byte转行成int: 156

测试的long值为:100000
long转行成bytes: 0 0 0 0 0 1 -122 -96 
bytes转行成long: 100000


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清缓

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值