byte,int,char,double的相互转换(java)
最近在学习一些SOCKET通讯协议设计的知识,涉及到了一些协议的设计,需要打包和解包,所以把一些比较基本的知识搜集了下来.
mfR#H2RqnQMF051Testing软件测试网 `!U"i?'cI Q8@暂时把协议结构定义得比较简单,也就是 CMD(命令类型8位)+序号(整形16位)+接收人长度(整形16位)+消息内容(每个包只接收1024位消息内容,多余的需要分割);下面是需要用到的一些方法.
\$G {V/},ZQ@i,W"J0%`
XX4@^!S]0//整数到字节数组的转换
PZA(P?f0 public byte[] intToByte(int intValue) {
2}^8VG
`0 byte[] result = new byte[4];51Testing软件测试网CLa cb/jF#C
result[0] = (byte) ( (intValue & 0xFF000000) >> 24);
`Qp2I3m0pm|0 result[1] = (byte) ( (intValue & 0x00FF0000) >> 16);51Testing软件测试网*W*a#[ p8Y
LX*cY
result[2] = (byte) ( (intValue & 0x0000FF00) >> 8);51Testing软件测试网TT qN9N_k
result[3] = (byte) ( (intValue & 0x000000FF));
YK9L r9{9M0 return result;51Testing软件测试网^"o1F k,x9f[6s
}51Testing软件测试网3}0|^M2unW8QY
//字节数组到整数的转换
kYjr(c0 public static int byteToInt(byte[] b) {
WQ1XtOsj2G%K0public static int byteToInt(byte[] byteVal) {51Testing软件测试网(m
Yzq$]u4s8U$F
int result = 0;
:W0a)T.|\8?"r0 for (int i = 0; i < byteVal.length; i++) {
c:A|#g-w"r&H0 int tmpVal = (byteVal[i] << (8 * (3 - i)));
*nj*Ig.v%WT6d2c0 switch (i) {51Testing软件测试网;J2y
JjgL^9q(Y/L
case 0:
5a'yd$B;E~~P9z0 tmpVal = tmpVal & 0xFF000000;51Testing软件测试网#z:r x9NN|s
break;
6H,Bj[8w+Xgg i1P0 case 1:
e(]BN
_%^(E1r \^0 tmpVal = tmpVal & 0x00FF0000;51Testing软件测试网0P]qSbi!?
break;51Testing软件测试网-y,}t\;FK.Z?
case 2:
9S`@5EjD5s#A$Dr.q8]0 tmpVal = tmpVal & 0x0000FF00;
e9xJ0NkIo*S~T1LZ O0 break;