欢迎来到天天文库
浏览记录
ID:8800629
大小:44.00 KB
页数:7页
时间:2018-04-08
《java基本类型与byte数组互相转换》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、publicclassConvToByte{/***short类型转换成byte数组**@paramparam*待转的short*@return**@authorli*@date2014-1-16上午10:03:47*/publicstaticbyte[]shortToByteArr(shortparam){byte[]arr=newbyte[2];arr[0]=(byte)((param>>8)&0xff);arr[1]=(byte)(param&0xff);returnarr;}/***int类型转换成byte数组**@paramparam*
2、待转的int*@return**@authorli*@date2014-1-16上午10:03:47*/publicstaticbyte[]intToByteArr(intparam){byte[]arr=newbyte[4];arr[0]=(byte)((param>>24)&0xff);arr[1]=(byte)((param>>16)&0xff);arr[2]=(byte)((param>>8)&0xff);arr[3]=(byte)(param&0xff);returnarr;}/***long类型转换成byte数组**@parampar
3、am*待转的long*@return**@authorli*@date2014-1-16上午10:03:47*/publicstaticbyte[]longToByteArr(longparam){byte[]arr=newbyte[8];arr[0]=(byte)((param>>56)&0xff);arr[1]=(byte)((param>>48)&0xff);arr[2]=(byte)((param>>40)&0xff);arr[3]=(byte)((param>>32)&0xff);arr[4]=(byte)((param>>24)&0x
4、ff);arr[5]=(byte)((param>>16)&0xff);arr[6]=(byte)((param>>8)&0xff);arr[7]=(byte)(param&0xff);returnarr;}/***字符到字节转换**@paramch*字符*@return**@authorli*@date2014-1-16下午4:10:07*/publicstaticbyte[]charToByteArr(charch){byte[]b=newbyte[2];inttemp=(int)ch;b[0]=(byte)(temp>>8&0xff);b[
5、1]=(byte)(temp&0xff);returnb;}/***double转换byte数组**@paramparam*double*@returnbyte数组**@authorli*@date2014-1-16下午4:45:57*/publicstaticbyte[]doubleToByteArr(doubleparam){byte[]b=newbyte[8];longl=Double.doubleToLongBits(param);for(inti=0;i6、;l=l>>8;}returnb;}/***float转换byte数组**@paramparam*float*@returnbyte数组**@authorli*@date2014-1-16下午5:05:04*/publicstaticbyte[]floatToByteArr(floatparam){byte[]b=newbyte[4];intl=Float.floatToIntBits(param);for(inti=0;i>8;}returnb;7、}/***将2字节的byte数组转成short值**@paramb*byte数组*@return**@authorli*@date2014-1-16下午3:00:01*/publicstaticshortbyteArrToShort(byte[]b){byte[]a=newbyte[2];inti=a.length-1,j=b.length-1;for(;i>=0;i--,j--){//从b的尾部(即int值的低位)开始copy数据if(j>=0)a[i]=b[j];else//如果b.length不足2,则将高位补0a[i]=0;}//&0xf8、f将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位intv0=(a[0]&0xff)<<8;intv1=(a
6、;l=l>>8;}returnb;}/***float转换byte数组**@paramparam*float*@returnbyte数组**@authorli*@date2014-1-16下午5:05:04*/publicstaticbyte[]floatToByteArr(floatparam){byte[]b=newbyte[4];intl=Float.floatToIntBits(param);for(inti=0;i>8;}returnb;
7、}/***将2字节的byte数组转成short值**@paramb*byte数组*@return**@authorli*@date2014-1-16下午3:00:01*/publicstaticshortbyteArrToShort(byte[]b){byte[]a=newbyte[2];inti=a.length-1,j=b.length-1;for(;i>=0;i--,j--){//从b的尾部(即int值的低位)开始copy数据if(j>=0)a[i]=b[j];else//如果b.length不足2,则将高位补0a[i]=0;}//&0xf
8、f将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位intv0=(a[0]&0xff)<<8;intv1=(a
此文档下载收益归作者所有