在使用Java的字节I/O流时,有时需要进行基本数据类型的数据与字节数据之间的转化,以下是转化方法。
// Convert.java
public classConvert {
/**
* 将short类型转化为byte[]数组
*
* @param id
* @return
*/
public static byte[] short2Bytes(short id) {
byte[] arr = new byte[2];
for (int i = 0; i < arr.length; i++)
arr[i] = (byte) ((id >> i * 8) & 0xff);
return arr;
}
/**
* 将byte[]数组转化为short类型
*
* @param arr
* @return
*/
public static short bytes2Short(byte[] arr) {
short result = 0;
for (int i = 0; i < arr.length; i++)
result += (arr[i] & 0xff) << i * 8;
return result;
}
/**
* 将int类型转化为byte[]数组
*
* @param id
* @return
*/
public static byte[] int2Bytes(int id) {
byte[] arr = new byte[4];
for (int i = 0; i < arr.length; i++)
arr[i] = (byte) ((id >> i * 8) & 0xff);
return arr;
}
/**
* 将byte[]数组转化为int类型
*
* @param arr
* @return
*/
public static int bytes2Int(byte[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++)
result += (arr[i] & 0xff) << i * 8;
return result;
}
/**
* 将long类型转化为byte[]数组
*
* @param id
* @return
*/
public static byte[] long2Bytes(long id) {
byte[] arr = new byte[8];
for (int i = 0; i < arr.length; i++)
arr[i] = (byte) ((id >> i * 8) & 0xff);
return arr;
}
/**
* 将byte[]转化为long类型
*
* @param arr
* @return
*/
public static long bytes2long(byte[] arr) {
long result = 0L;
for (int i = 0; i < arr.length; i++)
result += (long)(arr[i] & 0xff) << i * 8;
return result;
}
public static void main(String[] args) {
int i;
byte[] ars = Convert.short2Bytes(Short.MAX_VALUE);
System.out.println("将short类型的最大值转化为byte[]数组:");
for(i=0;i<ars.length;i++)
System.out.print(ars[i]+",");
System.out.println();
System.out.println("将byte[]数组转化为short:");
System.out.println(Convert.bytes2Short(ars));
System.out.println("将int类型的最大值转化为byte[]数组:");
byte[] ari = Convert.int2Bytes(Integer.MAX_VALUE);
for(i=0;i<ari.length;i++)
System.out.print(ari[i]+",");
System.out.println();
System.out.println("将byte[]数组转化为int:");
System.out.println(Convert.bytes2Int(ari));
System.out.println("将long类型的最大值转化为byte[]数组:");
byte[] arl = Convert.long2Bytes(Long.MAX_VALUE);
for(i=0;i<arl.length;i++)
System.out.print(arl[i]+",");
System.out.println();
System.out.println("将byte[]数组转化为long:");
System.out.println(Convert.bytes2long(arl));
System.out.println("将int类型的8143转化为byte[]数组:");
byte[] ar = Convert.int2Bytes(8143);
for(i=0;i<ar.length;i++)
System.out.print(ar[i]+",");
System.out.println();
// 字符串与字节数组的转化
Stringstr= "我喜欢Java";
byte[] arst = str.getBytes();
for(i=0;i<arst.length;i++)
System.out.print(arst[i]+",");
System.out.println();
Stringba = new String(arst);
System.out.println(ba);
}
}