Tuesday 5 January 2016

Java stores in big-endian format

As per Java specification, multibyte data items are always stored in big-endian order.


It is always good to know what is Big Endian, Little Endian and what are the differences.

Most Significant Bit and Least Significant Bit
The rightmost bit is the least significant bit, and the leftmost bit is the most significant bit.

For example, 1234567890 in decimal is represented as 1001001100101100000001011010010 in Binary. Left most bit is ‘1’ and right most bit is 0. So most significant bit is 1 and least significant bit is 0.

Most Significant Byte and Least Significant Byte
The rightmost byte is the least significant byte, and the leftmost byte is the most significant byte.

For example, 1234567890 number in decimal is represented as 1001001100101100000001011010010 (1001001 10010110 00000010 11010010) in Binary. MSB is 1001001 and LSB is 11010010.

Endianeness specifies how the order of bytes stored in Computer memory. Data in computer memory can be represented in any of two ways.
a.   Big Endian format
b.   Little Endian format

a. Big Endian format
In Big Endian format, Most Significant Byte stores in first address followed by subsequent bytes. For example, If you want to store 80CB12BD16, since it is in hexa decimal format, each hex digit is 4 bits, we need 8 hex digits to represent the 32 bit value. So the four bytes are 80, CB, 12, BD.

Address
Value
2000
80
2001
CB
2002
12
2003
BD

b. Little Endian format
In Big Endian format, Least Significant Byte stores in first address. For example, If you want to store 80CB12BD16, since it is in hexa decimal format, each hex digit is 4 bits, we need 8 hex digits to represent the 32 bit value. So the four bytes are 80, CB, 12, BD.

Address
Value
2000
BD
2001
12
2002
CB
2003
80

Java Endianness is not system dependent, even though your system supports Little-Endianness.


Following program tells you whether your system is BigEndian (or) Little Endian.
import java.nio.ByteOrder;

public class EndianNessTest {
  public static void main(String ptr[]) {
    if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)) {
      System.out.println("Big-endian");
    } else {
      System.out.println("Little-endian");
    }
  }
}



                                                 Home

No comments:

Post a Comment