socket编程采用的就是tcp/ip网络协议。
下面是java开发中一些常用的类型转换的方法:
//将int类型转换成字节数组 (高位在后,低位在前的顺序) 大段序
public static byte[] intToByte(int i) {
byte[] targets = new byte[4];
targets[0] = (byte) (i & 0xFF);
targets[1] = (byte) (i >> 8 & 0xFF);
targets[2] = (byte) (i >> 16 & 0xFF);
targets[3] = (byte) (i >> 24 & 0xFF);
return targets;
}
//将int类型转换成字节数组 (高位在前,低位在后的顺序) 小段序
public static byte[] intToByte2(int i) {
byte[] targets = new byte[4];
targets[3] = (byte) (i & 0xFF);
targets[2] = (byte) (i >> 8 & 0xFF);
targets[1] = (byte) (i >> 16 & 0xFF);
targets[0] = (byte) (i >> 24 & 0xFF);
return targets;
}
//将long类型转换成byte[]数组 (大端序,低位在前,高位在后)
public static byte[] longToByteArray(long s) {
byte[] targets = new byte[8];
for (int i = 0; i < 8; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[7-i] = (byte) ((s >>> offset) & 0xff);
}
return targets;
}
//byte数组中取int数值,本方法适用于(高位在前,低位在后)的顺序。小段序
public static int bytesToInt2(byte[] src, int offset) {
int value;
value = (int) ( ((src[offset] & 0xFF)<<24)
|((src[offset+1] & 0xFF)<<16)
|((src[offset+2] & 0xFF)<<8)
|(src[offset+3] & 0xFF));
return value;
}
// byte数组中取int数值,本方法适用于(高位在后,低位在前)的顺序。 大段序
public static int bytesToInt(byte[] src, int offset) {
int value;
value = (int) ( ((src[offset+3] & 0xFF)<<24)
|((src[offset+2] & 0xFF)<<16)
|((src[offset+1] & 0xFF)<<8)
|(src[offset+0] & 0xFF));
return value;
}
//byte[8]转long 大端序(低位在前,高位在后)
public static long byte2Long(byte[] b) {
return
((b[7]&0xff)<<56)|
((b[6]&0xff)<<48)|
((b[5]&0xff)<<40)|
((b[4]&0xff)<<32)|
((b[3]&0xff)<<24)|
((b[2]&0xff)<<16)|
((b[1]&0xff)<<8)|
(b[0]&0xff);
}
//byte[8]转long 大端序(低位在前,高位在后)
public static long byte2Long(byte[] b, int offset) {
return ((((long) b[offset + 7] & 0xff) << 56)
| (((long) b[offset + 6] & 0xff) << 48)
| (((long) b[offset + 5] & 0xff) << 40)
| (((long) b[offset + 4] & 0xff) << 32)
| (((long) b[offset + 3] & 0xff) << 24)
| (((long) b[offset + 2] & 0xff) << 16)
| (((long) b[offset + 1] & 0xff) << 8)
| (((long) b[offset + 0] & 0xff) << 0));
}