hongbin
hongbin

Reputation: 187

java numeric type conviersion when the underlying platform is big endian

I'm wondering what happens when I write the following java code on a big-endian platform:

int a = 1;
byte b = (byte)a;

On a little-endian platform, the layout of variable a's four bytes are x01000000, so converting a to a byte, we still get x01, which makes b equals to 1. However, on a big-endian platform, a is laid out as x00000001, so will b still equal to x01? If it does, how does this magic happen?

Upvotes: 0

Views: 33

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533482

Operations are performed in registers in the CPU, not in memory. Registers are neither big-endian nor little-endian and they are not randomly accessible.

In any case, the behaviour is defined in the Java Language Specification as keeping the lower bits in each case, so it wouldn't matter how the CPU works.

how does this magic happen?

No magic, the CPU just discards the higher bits. (Technically the CPU may also do a sign extension as many CPUs have 32-bit or 64-bit registers) How those bytes were stored in memory before it did this doesn't matter.

Upvotes: 1

Related Questions