在编写网络通信的时候通常会指定一个报头来说明C/S端数据的协议和内容体的长度,内容长度在java代码里面通常表现为一个int类型或是long类型,但是在将int或long弄写到通信管道的却需要将其转成字节数组。公司有人这样写:
String length = String.valueOf(request.getData().length);
while (length.length() < 4) {
length = "0" + length;
}
byte[] header=length.getBytes();
简直无法直视对吧,因看不惯这样的代码,本人决定写一个工具类来处理这些基础类型到byte数组的互换。下面贴上代码:
public static byte[] toBytes(int n) {
byte[] bytes = new byte[4];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
}
return bytes;
}
public static byte[] toBytes(long n) {
byte[] bytes = new byte[8];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
}
return bytes;
}
public static int toInt(byte[] bytes) {
int n = 0;
for (int i = 0; i < bytes.length; i++) {
n = n | ((bytes[i] & 0xff) << (i << 3));
}
return n;
}
public static long toLong(byte[] bytes) {
long n = 0;
for (int i = 0; i < bytes.length; i++) {
n = n | ((bytes[i] & 0xffL) << (i << 3));
}
return n;
}
public static byte[] toBytes(short n){
byte[] bytes=new byte[2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
}
return bytes;
}
public static byte[] toByte(char c){
return toBytes((short)c);
}
public static short toShort(byte[] bytes){
short n = 0;
for (int i = 0; i < bytes.length; i++) {
n = (short) (n | ((bytes[i] & 0xff) << (i << 3)));
}
return n;
}
public static char toChar(byte[] bytes){
return (char)toShort(bytes);
}
相信在大学里面好好学过C的人都能看懂这代码的意思,我就不作太多解释了 ^_^ 。
1个字节有8bit ,0xFF表示一个8位全1的字节,如果将其与一个int型数进行&运算则能取出此int的第1个字节。如果将0xff左移8位再与此int进行&运算则能取出它的第2个字节,依此类推. 从byte数组到int则是一个逆向的“或”(运算符“|” )过程。