Shift portability

R

Roger

Consider the expression:

(j & 0xFF0000 >> 16) == ((j & 0xFF0000) / 0x10000)

Is this **always** true by definition, or could the result vary
depending on the target/toolchain (processor word size, big/little
endian etc).
 
V

Vladimir S. Oka

E

Eric Sosman

Roger said:
Consider the expression:

(j & 0xFF0000 >> 16) == ((j & 0xFF0000) / 0x10000)

Is this **always** true by definition, or could the result vary
depending on the target/toolchain (processor word size, big/little
endian etc).

As written the equality seldom holds, because >>
"binds more tightly" than &. The l.h.s. is the same as

(j & (0xFF0000 >> 16))
or
j & 0xFF

The question you probably intended to ask was whether

(j & 0xFF0000) >> 16 == (j & 0xFF0000) / 0x10000

always holds. Assuming j is some kind of integer (of any
size and signedness), then yes: equality always holds.[*]

[*] Forestalling a mistake: Yes, it holds even if j is
a signed 24-bit int. On such a machine, 0xFF0000 will have
the type unsigned int, so j will be converted to unsigned
int before applying the & operator.
 

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

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,205
Latest member
ShereeStan

Latest Threads

Top