java 整数 字节数组_将整数转换为字节数组(Java)
看看
ByteBuffer類。
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();
設置字節順序確保result [0] == 0xAA,result [1] == 0xBB,result [2] == 0xCC和result [3] == 0xDD。
或者,您可以手動執行:
byte[] toBytes(int i)
{
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);
return result;
}
ByteBuffer類是為這樣的臟手任務設計的。實際上,私有java.nio.Bits定義了ByteBuffer.putInt()使用的這些幫助方法:
private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >> 8); }
private static byte int0(int x) { return (byte)(x >> 0); }
總結
以上是生活随笔為你收集整理的java 整数 字节数组_将整数转换为字节数组(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中鼠标事件_java中检测鼠标事
- 下一篇: java中this的含义_Javascr