Sunday, March 19, 2006
int to bytes
Here is a fun quiz: What is the best possible way (fastest with least memory) to convert an int to a byte array (of size 4) in big endian in Java ? ie.
Update on 21Mar06: Interesting class to look at java.nio.Bits.
Update on 29Mar06: Paul Brown has more details.
It turns out the code below is the best I've found so far:public static byte[] toBigEndianBytes(int i) {
// ??
}
Can you think of a better one ?public static byte[] toBigEndianBytes(int i) {
return new byte[] {
(byte)(i >>> 24),
(byte)(i >>> 16),
(byte)(i >>> 8),
(byte)i
};
}
Update on 21Mar06: Interesting class to look at java.nio.Bits.
Update on 29Mar06: Paul Brown has more details.