您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java字节流与基本数据类型的转换实例详解

2024/12/7 7:46:52发布15次查看
本篇文章主要介绍了java字节流与基本数据类型的转换实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在实际开发中,我们经常遇到与嵌入式进行通信的情况,而由于一些嵌入式设备的处理能力较差,往往以二进制的数据流的形式传输数据,在此将这些常见的转换做一总结。
注意:默认传输时使用小端模式
将字节流转换为int类型数据
public static int getint(byte[] bytes) { return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24)); }
将字节流转换为long类型数据
public static long getlong(byte[] bytes) { return ((0xffl & (long) bytes[0]) | (0xff00l & ((long) bytes[1] << 8)) | (0xff0000l & ((long) bytes[2] << 16)) | (0xff000000l & ((long) bytes[3] << 24)) | (0xff00000000l & ((long) bytes[4] << 32)) | (0xff0000000000l & ((long) bytes[5] << 40)) | (0xff000000000000l & ((long) bytes[6] << 48)) | (0xff00000000000000l & ((long) bytes[7] << 56))); }
将字节流转换为float类型数据
public static float getfloat(byte[] bytes){ int temp=getint(bytes); return float.intbitstofloat(temp); }
将字节流转换为double类型数据
public static double getdouble(byte[] bytes){ long temp=getlong(bytes); return double.longbitstodouble(temp); }
将int类型数据转换为字节流
public static byte[] getbytefromint(int data){ byte[] temp=new byte[4]; temp[0]=(byte)(0xff&(data)); temp[1]=(byte)(0xff&(data>>8)); temp[2]=(byte)(0xff&(data>>16)); temp[3]=(byte)(0xff&(data>>24)); return temp; }
将long类型数据转换为字节流
public static byte[] getbytefromlong(long data){ byte[] temp=new byte[8]; temp[0]=(byte)(0xff&(data)); temp[1]=(byte)(0xff&(data>>8)); temp[2]=(byte)(0xff&(data>>16)); temp[3]=(byte)(0xff&(data>>24)); temp[4]=(byte)(0xff&(data>>32)); temp[5]=(byte)(0xff&(data>>40)); temp[6]=(byte)(0xff&(data>>48)); temp[7]=(byte)(0xff&(data>>56)); return temp; }
将float类型数据转换为字节流
public static byte[] getbytefromfloat(float data){ byte[] temp=new byte[4]; int tempint=float.floattointbits(data); temp[0]=(byte)(0xff&(tempint)); temp[1]=(byte)(0xff&(tempint>>8)); temp[2]=(byte)(0xff&(tempint>>16)); temp[3]=(byte)(0xff&(tempint>>24)); return temp; }
将double类型数据转换为字节流
public static byte[] getbytefromdouble(double data){ byte[] temp=new byte[8]; long templong=double.doubletolongbits(data); temp[0]=(byte)(0xff&(templong)); temp[1]=(byte)(0xff&(templong>>8)); temp[2]=(byte)(0xff&(templong>>16)); temp[3]=(byte)(0xff&(templong>>24)); temp[4]=(byte)(0xff&(templong>>32)); temp[5]=(byte)(0xff&(templong>>40)); temp[6]=(byte)(0xff&(templong>>48)); temp[7]=(byte)(0xff&(templong>>56)); return temp; }
以上就是java字节流与基本数据类型的转换实例详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product