write a function that determines whether a computer is big endian or little endian in java [duplicate]

StackOverflow https://stackoverflow.com/questions/21447526

  •  04-10-2022
  •  | 
  •  

質問

I've reed this code which is in C format but i didn't understand what's the process exactly. can anyone explain it for me in java or if there is a better way in java could you please write it here? thank you

bool endianess(){
 int testNum;
 char *ptr;

 testNum=1;
 ptr=(char*) &testNum;
 return (*ptr); //* return the byte at the lowest address
}
役に立ちましたか?

解決

In a Little Endian architecture, the integer value 0x1 will be written out in memory like

0x1 0x0 0x0 ....

so that function will return 1

Conversely, in a Big Endian architecture, the order of bytes will be

0x0 0x0 ... 0x1

however many bytes are in an int (greater or equal to 2 for it to work), and so

this function will return 0.

Here's a reference for why it can't be done in Java directly, but you could use JNI to escape out to a C library and return the result.

他のヒント

You may use System.getProperty("sun.cpu.endian"). Alternately, you may use SIGAR (https://github.com/hyperic/sigar), Java native access, JNI etc. to get this information.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top