Reputation: 4275
Consider the following code:
long store;
int firstValue = 0x1234;
int secondValue = 0x5678;
store = (((long) firstValue) << 32) | secondValue;
Is store
guaranteed to have the value 0x12345678
regardless of the endianess of the machine...
Upvotes: 2
Views: 774
Reputation: 385799
Endianness doesn't matter, although whether the machine uses one's complement or two's complement can.
<<
is unaffected because it is defined in terms of arithmetic operations (multiplication and exponentiation).<<
is unaffected because it is defined in terms of arithmetic operations (multiplication, exponentiation, addition, arithmetic negation and subtraction).|
is defined in terms of the underlying bits. Endianness would have no effect, but it can behave differently on a ones' complement machine than on a two's complement machine.|
is unaffected because Java integers are always two's complement.I presume that C++ is the same as C.
Upvotes: 1
Reputation: 234474
The bitshift operations in all those languages operate on numbers. Endianness is not a property of numbers.
In Java store
is guaranteed to have the value 0x123400005678L
, because 0x1234L << 32
is 0x123400000000L
.
In C and C++ store
is not guaranteed to have any particular value: the result depends on the sizes of the types involved, and it has potentially undefined behaviour due to overflows (long
is allowed to be as small as 32 bits, and it actually is so in some mainstream implementations). If no overflows occur, then the result is the same as in Java.
Upvotes: 8
Reputation: 254461
I assume you mean to shift by 16 bits, not 32, to get 0x12345678
. Shifting by 32 will overflow in Java, and in most C/C++ implementations.
That is guaranteed, and independent of endianness. Endianness determines how multi-byte values are stored in memory, not which bits are logically in which position within the value. Left-shifting by N bits is always equivalent to multiplying by 2N.
Upvotes: 2