最近在接手了java的数据通信,由于是别人做了一半的,所以各种分工不同步、未测试而遗留的bug是一个接着一个。经过两周的努力,总算是把各种问题、功能都调教好了。趁此,做个基本类型与byte[]的转换。
public class Conclude {
/**
* 测试类
* @param args
*/
public static void main(String[] args) {
double test = -0.123;
System.out.println(Conclude.doubleToBytes(test));
System.out.println(Conclude.bytesToDouble(Conclude.doubleToBytes(test)));
}
public static byte[] longToBytes(long num) {
long temp = num;
byte[] b = new byte[8];
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();
temp = temp >> 8;
}
return b;
}
/**
* @param 设b的长度为8
* @return
*/
public static long bytesToLong(byte[] b) {
long num = 0;
long temp = 0;
for (int i = 0; i < b.length; i++) {
temp = b[i] & 0xff;
temp <<= 8 * i;
num = num | temp;// 此处或的效果和加是相同的,但是或操作的效率要高一些
}
return num;
}
public static byte[] intToBytes(int num) {
int temp = num;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();
temp = temp >> 8;
}
return b;
}
/**
* @param 设byte的长度为4
* @return
*/
public static int bytesToInt(byte[] b) {
int num = 0;
int temp = 0;
for (int i = 0; i < b.length; i++) {
temp = b[i] & 0xff;
temp <<= 8 * i;
num = num | temp;
}
return num;
}
public static byte[] doubleToBytes(double d) {
byte b[] = new byte[8];
// 根据 IEEE 754 浮点双精度格式 ("double format") 位布局,返回指定浮点值的表示形式
long v = Double.doubleToLongBits(d);
b[0] = (byte) (v >>> 56);// 发现写死的话比for循环效率高那么一丢丢。。。
b[1] = (byte) (v >>> 48);
b[2] = (byte) (v >>> 40);
b[3] = (byte) (v >>> 32);
b[4] = (byte) (v >>> 24);
b[5] = (byte) (v >>> 16);
b[6] = (byte) (v >>> 8);
b[7] = (byte) (v >>> 0);
return b;
}
public static double bytesToDouble(byte[] b) {
return Double.longBitsToDouble((((long) b[0] << 56) + ((long) (b[1] & 0xff) << 48)
+ ((long) (b[2] & 0xff) << 40) + ((long) (b[3] & 0xff) << 32) + ((long) (b[4] & 0xff) << 24)
+ ((b[5] & 0xff) << 16) + ((b[6] & 0xff) << 8) + ((b[7] & 0xff) << 0)));
}
}
会做这个总结,是因为数据的通信经常用byte即8bit为单位进行数据的传输。而接收和发送数据,就需要数据进行编码解码。以上代码采用的是一般使用的byte[]和其他数据类型的转换。当然,也可以自己定规则喽,但是这个是最实用的,貌似jdk中也用的这种转换方式。