public byte[] intToByteArray (final int integer) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(integer); dos.flush(); return bos.toByteArray(); }
谢谢楼上的提醒。 final 在数值型参数前没什么意义。放在对象型的参数前可以防止该方法影响调用方法中实参的状态。
我刚才也测了一下,的确不起做用。“Changes for Java 1.1”文档里提到了。里面的原话是这样的: Method parameters and local variables can be declared final. If you do not expect to change the value of a parameter or variable inside the method, you can declare it final to let the compiler enforce that. The compiler can also optimize uses of a final parameter or variable since it knows the value will never change.
int tmp = Integer.MAX_VALUE - 2134345;
System.out.println(Integer.toHexString(tmp));
byte[] rs = new byte[4];
for (int i = 0; i < 4; i++) {
rs[i] = (byte) (tmp & 0xFF);
System.out.println(Integer.toHexString(rs[i] & 0xFF));
tmp = tmp >> 8;//右移8位
}
}测试数据:
7fdf6eb6
b6
6e
df
7f
更多细节查阅我以前写的一篇文章
http://blog.csdn.net/sunyujia/archive/2008/05/04/2385727.aspx
就是有点麻烦,偶还是另想办法.
byte[] byteArray = new byte[4];
byteArray[0] = (byte)((number >> 24) & 0xFF);
byteArray[1] = (byte)((number >> 16) & 0xFF);
byteArray[2] = (byte)((number >> 8) & 0xFF);
byteArray[3] = (byte)(number & 0xFF);
}也可以用另外一种的方式:
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
public byte[] intToByteArray (final int integer) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(integer);
dos.flush();
return bos.toByteArray();
}
容纳后用getBytes
Method parameters and local variables can be declared final. If you do not expect to change the value of a parameter or variable inside the method, you can declare it final to let the compiler enforce that. The compiler can also optimize uses of a final parameter or variable since it knows the value will never change.
ByteBuffer buff=ByteBuffer.allocate(4);
buff.putInt(i);
byte []bytes=buff.array();
而 Windows 平台采用的字节序是 Little-Endian 即低字节位位于低地址中。也就是说转换的关键在于:高字节位位于字节数组的索引 0 上,还是索引 3 上。
16楼的是根据nio来的,效率来说应该比8楼低吧