0

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
}
faranak777
  • 451
  • 7
  • 17

2 Answers2

4

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.

Community
  • 1
  • 1
waTeim
  • 8,830
  • 2
  • 35
  • 39
1

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.

Nipun Talukdar
  • 4,566
  • 4
  • 29
  • 40