Shift portability

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Roger

    #1

    Shift portability

    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).

  • Vladimir S. Oka

    #2
    Re: Shift portability


    Roger wrote:[color=blue]
    > 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).[/color]

    Shifts operate on the value, not representation. For a detailed
    descussion of the finer points, have a look at this thread:



    --
    BR, Vladimir

    Comment

    • Eric Sosman

      #3
      Re: Shift portability

      Roger wrote:
      [color=blue]
      > 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).[/color]

      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.

      --
      Eric Sosman
      esosman@acm-dot-org.invalid

      Comment

      Working...