char double java_byte,int,char,double的相互转换(java)

最近在学习一些SOCKET通讯协议设计的知识,涉及到了一些协议的设计,需要打包和解包,所以把一些比较基本的知识搜集了下来.

暂时把协议结构定义得比较简单,也就是 CMD(命令类型8位)+序号(整形16位)+接收人长度(整形16位)+消息内容(每个包只接收1024位消息内容,多余的需要分割);下面是需要用到的一些方法.

//整数到字节数组的转换

public byte[] intToByte(int intValue) {

byte[] result = new byte[4];

result[0] = (byte) ( (intValue & 0xFF000000) >> 24);

result[1] = (byte) ( (intValue & 0x00FF0000) >> 16);

result[2] = (byte) ( (intValue & 0x0000FF00) >> 8);

result[3] = (byte) ( (intValue & 0x000000FF));

return result;

}

//字节数组到整数的转换

public static int byteToInt(byte[] b) {

public static int byteToInt(byte[] byteVal) {

int result = 0;

for (int i = 0; i < byteVal.length; i++) {

int tmpVal = (byteVal[i] << (8 * (3 - i)));

switch (i) {

case 0:

tmpVal = tmpVal & 0xFF000000;

break;

case 1:

tmpVal = tmpVal & 0x00FF0000;

break;

case 2:

tmpVal = tmpVal & 0x0000FF00;

break;

case 3:

tmpVal = tmpVal & 0x000000FF;

break;

}

result = result | tmpVal;

}

return result;

}

//字符到字节转换

public static byte[] charToByte(char ch){

int temp=(int)ch;

byte[] b=new byte[2];

for (int i=b.length-1;i>-1;i--){

b = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位

temp = temp >> 8;       //向右移8位

}

return b;

}

//字节到字符转换

public static char byteToChar(byte[] b){

int s=0;

if(b[0]>0)

s+=b[0];

else

s+=256+b[0];

s*=256;

if(b[1]>0)

s+=b[1];

else

s+=256+b[1];

char ch=(char)s;

return ch;

}

//浮点到字节转换

public static byte[] doubleToByte(double d){

byte[] b=new byte[8];

long l=Double.doubleToLongBits(d);

for(int i=0;i

b=new Long(l).byteValue();

l=l>>8;

}

return b;

}

//字节到浮点转换

public static double byteToDouble(byte[] b){

long l;

l=b[0];

l&=0xff;

l|=((long)b[1]<<8);

l&=0xffff;

l|=((long)b[2]<<16);

l&=0xffffff;

l|=((long)b[3]<<24);

l&=0xffffffffl;

l|=((long)b[4]<<32);

l&=0xffffffffffl;

l|=((long)b[5]<<40);

l&=0xffffffffffffl;

l|=((long)b[6]<<48);

l&=0xffffffffffffffl;

l|=((long)b[7]<<56);

return Double.longBitsToDouble(l);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值