1 字符串转换成byte数组
public static void SaveStringsToBytes(byte[] byteBuf , String[] string){
int arraylen = string.length;
for(int i = 0 ; i < arraylen ; i++){
byteBuf[i *DATA_LEN]= (byte)string[i].length();
System.arraycopy( string[i].getBytes() , 0 ,byteBuf , i * DATA_LEN + 1, string[i].length() );
}
}
2 byte数组转换成字符串
public static void GetStringsFromBytes(byte[] byteBuf , String[] string)
{
byte[] strbytes = new byte[MAX_LEN];
int len = 0;
for(int i = 0 ; i < MAX_NUM ; i++){
len = byteBuf[i * (DATA_LEN) ];
System.arraycopy( byteBuf , i * (DATA_LEN) + 1 , strbytes , 0 , MAX_LEN);
string[i] = new String(strbytes , 0 , len);
}
}
3 整型转换成byte数组
public static void SaveIntsToBytes(byte[] byteBuf , int[] intbuf){
int arraylen = intbuf.length;
for(int i = 0 ; i < arraylen ; i++) {
byte[] temp = new byte[4];
temp[0] = (byte)(intbuf[i] & 0xFF);
temp[1] = (byte)((intbuf[i] >> 8)& 0xFF);
temp[2] = (byte)((intbuf[i] >> 16)& 0xFF);
temp[3] = (byte)((intbuf[i] >> 24)& 0xFF);
System.arraycopy( temp , 0 , byteBuf , i * 4, 4);
}
}
4 byte数组转换成整型
public static void GetIntsFromBytes(byte[] byteBuf , int[] intbuf){
byte[] temp = new byte[4];
for(int i = 0 ; i < byteBuf.length/4 ; i++) {
System.arraycopy( byteBuf , i * 4 , temp , 0 , 4);
intbuf[i] =(int)( (temp[0]&0xFF) + ((temp[1]<< 8)&0xFFFFFFFF ) +
((temp[2] <<16) &0xFFFFFFFF ) +((temp[3] << 24) &0xFFFFFFFF ));
}
}
5 字节流转换成char
public static void byteToChar(byte[] byteBuf , char[] charbuf,int length){
for(int i = 0,j=0 ; i < length ; i+= 2,j++){
charbuf [j] = (char) ((char)byteBuf[i] | (char)(byteBuf[i+1])<<8);
}
}
6. 从流到Java程序byte——〉char
7. 从Java程序到流char——〉byte
8. 从文件到Java程序 byte——〉char
9. 从Java程序到文件 char——〉byte