3

In C I could the Endianess of the machine by the following method. how would I get using a python or Java program?. In Java, char is 2-bytes unlike C where it is 1-byte. I think it might not be possible with python since it is a dynamic language, but I could be wrong

bool isLittleEndian()
     {
       // 16 bit value, represented as 0x0100 on Intel, and 0x0001 else
       short pattern = 0x0001;
       // access first byte, will be 1 on Intel, and 0 else
       return *(char*) &pattern == 0x01;
     }
brain storm
  • 30,124
  • 69
  • 225
  • 393

4 Answers4

7

In Java, it's just

ByteOrder.nativeOrder();

...which returns either BIG_ENDIAN or LITTLE_ENDIAN.

http://docs.oracle.com/javase/6/docs/api/java/nio/ByteOrder.html

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • But you only need to know this if you are dealing in "odd" interfaces (such as nio) that operate on machine-level data buffers, etc. – Hot Licks Dec 09 '14 at 17:35
4

The (byte) cast of short is defined in both Java and C to return the "little" end of the short, regardless of the endianness of the processor. And >> is defined to shift from "big" end to "little" end (and << the opposite), regardless of the endianness of the processor. Likewise +, -, *, /, et al, are all defined to be independent of processor endianness.

So no sequence of operations in Java or C will detect endianness. What is required is some sort of "alias" of one size value on top of another (such as taking the address of an int and casting to char*), but Java does not have any way to do this.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • Thanks for the answer. Please have a look at this: http://www.bits.stephan-brumme.com/endianess.html; I am more familiar with Java than C. thats why I was interested to get endianess in Java using bitwise operations than using ByteOrder.native.Order() – brain storm Jan 31 '14 at 19:55
  • 1
    @user1988876 - The routine at the top of that page is C code, and it uses aliasing of `short` and `char` to do its dirty work. As I said, there's no way to do such aliasing in Java. – Hot Licks Jan 31 '14 at 20:06
  • Thx for pointing out the error in my post... deleting it since I hate bad info, and was clearly incorrect in my post. – Zak Feb 03 '14 at 22:39
3

You can use sys.byteorder:

>>> import sys
>>> print sys.byteorder
'little'

Or you can get endianness by yourself with a little help of the built-in struct module:

import struct

def is_little():
    packed = struct.pack("i", 1)
    return packed[0] == "\x01";

print is_little()

That was all Python of course.

Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
3
import java.nio.ByteOrder;

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

valter