Endians and c++

K

Kalle Rutanen

Hi

Is it endian-safe to use bit operations in C++ ?

For example bit-shifts, does the left shift by n always equal
multiplicication by 2^n (modulo 2^integerBits), independent of endian
system used ?
 
V

Victor Bazarov

Kalle said:
Is it endian-safe to use bit operations in C++ ?

For example bit-shifts, does the left shift by n always equal
multiplicication by 2^n (modulo 2^integerBits), independent of endian
system used ?

Yes. The bit shifts operate on the number _value_, the representation
of the number in memory has nothing to do with it.

V
 
M

msalters

Kalle said:
Hi

Is it endian-safe to use bit operations in C++ ?

For example bit-shifts, does the left shift by n always equal
multiplicication by 2^n (modulo 2^integerBits), independent of endian
system used ?

No, but that's actually unrelated to endianness. Multiplication by
2^-1 is well defined, but a left shift over -1 bits isn't.
Overflow is undefined for signed types.

For unsigned types and positive n, the result is in fact defined as if
done by multiplication or division. (5.8 Shift operations)

HTH,
Michiel Salters
 
V

Victor Bazarov

msalters said:
No, but that's actually unrelated to endianness. Multiplication by
2^-1 is well defined, but a left shift over -1 bits isn't.

Wouldn't left shift by a negative number be the same as right shift by
the absolute value of the number? I mean, theoretically, of course.

V
 
M

msalters

Victor said:
Wouldn't left shift by a negative number be the same as right shift by
the absolute value of the number? I mean, theoretically, of course.

Yes, of course. If the shift operand is a literal or a constant, this
can
be an automatic transformation. However, if the rhs is a variable, this
cannot be done at compile-time. Now, apparently some CPU's dont't like
negative arguments, and it would be bad if they have have to implement
every << as (IF RHS<0 (NEG RHS, SHR RHS) ELSE SHL RHS ). This can be
done in C++ if needed, but you don't pay if you don't need it.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top