Google
 
Web unafbapune.blogspot.com

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.
public static byte[] toBigEndianBytes(int i) {
// ??
}
It turns out the code below is the best I've found so far:
public static byte[] toBigEndianBytes(int i) {
return new byte[] {
(byte)(i >>> 24),
(byte)(i >>> 16),
(byte)(i >>> 8),
(byte)i
};
}
Can you think of a better one ?

Update on 21Mar06: Interesting class to look at java.nio.Bits.
Update on 29Mar06: Paul Brown has more details.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?