Friday, August 7, 2009

ByteOrder: Especially Useful with Groovy Scripts

The Java New I/O (NIO) class ByteOrder can be useful in determining the native byte order (or Endianness) used by the underlying platform. Knowledge of a particular platform's endianness is vital when working with files.

The following simple Java code demonstrates how easy it is to call the static method ByteOrder.nativeOrder() to determine the host platform's byte order.

ReportEndian.java

import java.nio.ByteOrder;

public class ReportEndian
{
public static void main(final String[] arguments)
{
System.out.println("This machine's native byte order is " + ByteOrder.nativeOrder());
}
}


Running this simple code will generate this output (on the Intel-powered machine I am currently using):



Because Intel processors use Little Endian (see their white paper on this), it is not surprising that the result of calling ByteOrder.nativeOrder is LITTLE_ENDIAN on this machine.

This is another example of where Groovy can be a particularly powerful scripting language. While enjoying scripting language advantages offered by fellow scripting languages such as Ruby, Perl, and Python, Groovy also has access to the Java SDK and to classes like ByteOrder. A script written in Groovy can easily use the Java-provided ByteOrder.nativeOrder() to determine the byte ordering used on the host machine and process accordingly.

The next example shows how easy it is to do this with Groovy. In this case, I won't even bother creating a Groovy file, but will run Groovy command-line with the -e option specifying the simple Groovy code needed to evaluate the native byte order."



In a script that needed to know which endianness the particular host used, this would be a very valuable piece of information.


Conclusion

The JDK has introduced some features such as NIO that embrace platform-specific features through portable interfaces. These features, such as the ByteOrder.nativeOrder() method, can be especially useful when used in conjunction with the Groovy scripting language to write scripts that can take advantage of platform specific efficiencies.

No comments: