但也有人說他的方法比其他使用 "magic" ByteBuffer 好~。
我也不知道哪種好,所以都先記錄起來 XD
這裡記錄的程式碼是直接轉錄 [1] 的,所以都是把 Inteter 轉成 byte array。
方法一:
1 2 3 4 5 |
byte [] bytes = ByteBuffer.allocate( 4 ).putInt( 1695609641 ).array(); for ( byte b : bytes) { System.out.format( "0x%x " , b); } |
方法二:
1 2 3 4 5 6 7 |
public static final byte [] intToByteArray( int value) { return new byte [] { ( byte )(value >>> 24 ), ( byte )(value >>> 16 ), ( byte )(value >>> 8 ), ( byte )value}; } |
方法三:
1 |
BigInteger.valueOf( 1695609641 ).toByteArray() |
如果要把 byte array 轉回 integer,可以參考 [4] 的回應。
1 |
ByteBuffer.wrap(bytes).getInt(); |
另外~上述的程式碼都用長度為 4 的 byte array,是因為 Java 的 Integer 長度是 32-bit。
Primitive Data Type 的長度要複習的話,可以參考 [2]。
參考資料:
1、Java integer to byte array
2、The Java Tutorial: Primitive Data Types
3、How to convert a Java Long to byte[] for Cassandra?
4、How to convert a byte array to its numeric value (Java)?
沒有留言:
張貼留言