java byte数组与int,long,short,byte的转换实现方法
实例如下:
publicclassDataTypeChangeHelper{ /** *将一个单字节的byte转换成32位的int * *@paramb *byte *@returnconvertresult */ publicstaticintunsignedByteToInt(byteb){ return(int)b&0xFF; } /** *将一个单字节的Byte转换成十六进制的数 * *@paramb *byte *@returnconvertresult */ publicstaticStringbyteToHex(byteb){ inti=b&0xFF; returnInteger.toHexString(i); } /** *将一个4byte的数组转换成32位的int * *@parambuf *bytesbuffer *@parambyte[]中开始转换的位置 *@returnconvertresult */ publicstaticlongunsigned4BytesToInt(byte[]buf,intpos){ intfirstByte=0; intsecondByte=0; intthirdByte=0; intfourthByte=0; intindex=pos; firstByte=(0x000000FF&((int)buf[index])); secondByte=(0x000000FF&((int)buf[index+1])); thirdByte=(0x000000FF&((int)buf[index+2])); fourthByte=(0x000000FF&((int)buf[index+3])); index=index+4; return((long)(firstByte<<24|secondByte<<16|thirdByte<<8|fourthByte))&0xFFFFFFFFL; } /** *将16位的short转换成byte数组 * *@params *short *@returnbyte[]长度为2 **/ publicstaticbyte[]shortToByteArray(shorts){ byte[]targets=newbyte[2]; for(inti=0;i<2;i++){ intoffset=(targets.length-1-i)*8; targets[i]=(byte)((s>>>offset)&0xff); } returntargets; } /** *将32位整数转换成长度为4的byte数组 * *@params *int *@returnbyte[] **/ publicstaticbyte[]intToByteArray(ints){ byte[]targets=newbyte[2]; for(inti=0;i<4;i++){ intoffset=(targets.length-1-i)*8; targets[i]=(byte)((s>>>offset)&0xff); } returntargets; } /** *longtobyte[] * *@params *long *@returnbyte[] **/ publicstaticbyte[]longToByteArray(longs){ byte[]targets=newbyte[2]; for(inti=0;i<8;i++){ intoffset=(targets.length-1-i)*8; targets[i]=(byte)((s>>>offset)&0xff); } returntargets; } /**32位int转byte[]*/ publicstaticbyte[]int2byte(intres){ byte[]targets=newbyte[4]; targets[0]=(byte)(res&0xff);//最低位 targets[1]=(byte)((res>>8)&0xff);//次低位 targets[2]=(byte)((res>>16)&0xff);//次高位 targets[3]=(byte)(res>>>24);//最高位,无符号右移。 returntargets; } /** *将长度为2的byte数组转换为16位int * *@paramres *byte[] *@returnint **/ publicstaticintbyte2int(byte[]res){ //res=InversionByte(res); //一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000 inttargets=(res[0]&0xff)|((res[1]<<8)&0xff00);//|表示安位或 returntargets; } }
以上就是小编为大家带来的javabyte数组与int,long,short,byte的转换实现方法全部内容了,希望大家多多支持毛票票~