java中int与byte的相互转换
2013-03-19 14:39
483 查看
我们都知道,J***A中的基本数据类型有int,byte,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的J***A语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数据,而网络上的数据都是byte数据流,这就需要一个int-> byte[]与byte[] -> int的方法。
简单的方法,我们可以用DataOutputStream与ByteArrayOutputStream来将int转换成byte[],方法就是:
执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStream与ByteArrayInputStream。
下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。
注:numberOfLeadingZeros(int i) 在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量
简单的方法,我们可以用DataOutputStream与ByteArrayOutputStream来将int转换成byte[],方法就是:
int i = 0; ByteArrayOutputStream boutput = new ByteArrayOutputStream(); DataOutputStream doutput = new DataOutputStream(boutput); doutput.writeInt(i); byte[] buf = boutput.toByteArray();
执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStream与ByteArrayInputStream。
byte[] buf = new byte[4]; ByteArrayInputStream bintput = new ByteArrayInputStream(buf); DataInputStream dintput = new DataInputStream(); int i = dintput.readInt();
下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。
注:numberOfLeadingZeros(int i) 在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量
//int -> byte[] privatebyte[] intToByteArray(final int integer) { int byteNum = (40 -Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/ 8; byte[] byteArray = new byte[4]; for (int n = 0; n < byteNum; n++) byteArray[3 - n] = (byte) (integer>>> (n * 8)); return (byteArray); } //byte[] -> int public static int byteArrayToInt(byte[] b, int offset) { int value= 0; for (int i = 0; i < 4; i++) { int shift= (4 - 1 - i) * 8; value +=(b[i + offset] & 0x000000FF) << shift; } return value; }两种Int->byte[]的方法如下示例代码所示
import java.io.*; public class IOTest { public static void main(String[] args) throws Exception { int i = 65535; byte[] b = intToByteArray1(i); for(byte bb : b) { System.out.print(bb + " "); } } public static byte[] intToByteArray1(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF); result[1] = (byte)((i >> 16) & 0xFF); result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF); return result; } public static byte[] intToByteArray2(int i) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); out.writeInt(i); byte[] b = buf.toByteArray(); out.close(); buf.close(); return b; }
相关文章推荐
- byte,int,char,double的相互转换(java)
- java中int与byte〔4〕的相互转换
- java中byte数组与int类型之间的相互转换(两种方式)
- java中byte数组与int类型之间的相互转换(两种方式)
- java中int与byte的相互转换
- java中int、long与byte数组相互转换
- java int与byte[]数组的相互转换 补码
- Java中有关byte和String的转换笔记和byte[]到short、int、long的相互转换
- java中的int类型和byte数组的相互转换
- 在Java中int和byte[]的相互转换
- JAVA byte[], int, long三者之间的相互转换代码
- java中int与byte〔4〕的相互转换
- JAVA中int与byte[]的相互转换
- java中 int和byte相互转换
- Java中int和byte的相互转换
- [转]java中byte转换int时为何与0xff进行与运算
- java学习笔记1 int与byte的转换
- Java语法练习:String和Int、Double、Boolean的相互转换
- C++ int 与 byte[] 的相互转换
- java中byte转换int时为何与0xff进行与运算