java整数与byte数组的转换实现代码
java整数与byte数组的转换实现代码
这里对java中整数与byte数组的转换进行了实现,平时的项目中很少用的到,但是特定需求的时候还是需要的,这里就记录下,亲测可用,
实现代码:
publicclassNumberUtil{
/**
*int整数转换为4字节的byte数组
*
*@parami
*整数
*@returnbyte数组
*/
publicstaticbyte[]intToByte4(inti){
byte[]targets=newbyte[4];
targets[3]=(byte)(i&0xFF);
targets[2]=(byte)(i>>8&0xFF);
targets[1]=(byte)(i>>16&0xFF);
targets[0]=(byte)(i>>24&0xFF);
returntargets;
}
/**
*long整数转换为8字节的byte数组
*
*@paramlo
*long整数
*@returnbyte数组
*/
publicstaticbyte[]longToByte8(longlo){
byte[]targets=newbyte[8];
for(inti=0;i<8;i++){
intoffset=(targets.length-1-i)*8;
targets[i]=(byte)((lo>>>offset)&0xFF);
}
returntargets;
}
/**
*short整数转换为2字节的byte数组
*
*@params
*short整数
*@returnbyte数组
*/
publicstaticbyte[]unsignedShortToByte2(ints){
byte[]targets=newbyte[2];
targets[0]=(byte)(s>>8&0xFF);
targets[1]=(byte)(s&0xFF);
returntargets;
}
/**
*byte数组转换为无符号short整数
*
*@parambytes
*byte数组
*@returnshort整数
*/
publicstaticintbyte2ToUnsignedShort(byte[]bytes){
returnbyte2ToUnsignedShort(bytes,0);
}
/**
*byte数组转换为无符号short整数
*
*@parambytes
*byte数组
*@paramoff
*开始位置
*@returnshort整数
*/
publicstaticintbyte2ToUnsignedShort(byte[]bytes,intoff){
inthigh=bytes[off];
intlow=bytes[off+1];
return(high<<8&0xFF00)|(low&0xFF);
}
/**
*byte数组转换为int整数
*
*@parambytes
*byte数组
*@paramoff
*开始位置
*@returnint整数
*/
publicstaticintbyte4ToInt(byte[]bytes,intoff){
intb0=bytes[off]&0xFF;
intb1=bytes[off+1]&0xFF;
intb2=bytes[off+2]&0xFF;
intb3=bytes[off+3]&0xFF;
return(b0<<24)|(b1<<16)|(b2<<8)|b3;
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!