how to get endianess in Java or python?

无人久伴 提交于 2019-12-01 06:16:29

问题


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;
     }

回答1:


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




回答2:


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.




回答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




回答4:


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.



来源:https://stackoverflow.com/questions/21341325/how-to-get-endianess-in-java-or-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!