ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);
byte[] result = b.array();
private byte[] bigIntToByteArray( final int i ) {
BigInteger bigInt = BigInteger.valueOf(i);
return bigInt.toByteArray();
}
使用 DataOutputStream:
private byte[] intToByteArray ( final int i ) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(i);
dos.flush();
return bos.toByteArray();
}
使用 ByteBuffer:
public byte[] intToBytes( final int i ) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(i);
return bb.array();
}
public byte[] toByteArray(int value)
{
final byte[] destination = new byte[Integer.BYTES];
for(int index = Integer.BYTES - 1; index >= 0; index--)
{
destination[i] = (byte) value;
value = value >> 8;
};
return destination;
};
public void getBytes(int val) {
byte[] bytes = new byte[Integer.BYTES];
for (int i = 0;i < bytes.length; i ++) {
int j = val % Byte.MAX_VALUE;
bytes[i] = (j == 0 ? Byte.MAX_VALUE : j);
}
}
还有 Stringy 方法:
public void getBytes(int val) {
String hex = Integer.toHexString(val);
byte[] val = new byte[hex.length()/2]; // because byte is 2 hex chars
for (int i = 0; i < hex.length(); i+=2)
val[i] = Byte.parseByte("0x" + hex.substring(i, i+2), 16);
return val;
}