how to get endianess in Java or python?

后端 未结 4 1124
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 05:08

In C I could the Endianess of the machine by the following method. how would I get using a python or Java program?. In Ja

相关标签:
4条回答
  • 2021-01-14 05:28

    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.

    0 讨论(0)
  • 2021-01-14 05:32

    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

    0 讨论(0)
  • 2021-01-14 05:32
    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

    0 讨论(0)
  • 2021-01-14 05:46

    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.

    0 讨论(0)
提交回复
热议问题