转载请注明出处!
原文链接: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