Skip navigation

Here’s a C++ function:

// Little endian (little end/lsb first)
inline UInt32 RGBA( Byte R, Byte G, Byte B, Byte A )
{
  return A<<(3*8) + B<<(2*8) + G<<(8) + R ; //LE
  //return R<<(3*8) + G<<(2*8) + B<<(8) + A ; //BE
}

What’s wrong with it?. Why doesn’t it return the correct value? Try and guess! No cheating!

Is it the bitshifting being wrong? No, that’s right

Is it that R, G, B, and A are Byte type, and Byte overflows? Nope, they are automatically promoted to int.

So guess what it is? GUESS!

YOU KNEW IT!! OPERATOR PRECEDENCE!

Bitshift has a precedence lower than +. So the shifting is off (and by WAY too much in most cases!)

// Little endian (little end/lsb first)
inline UInt32 RGBA( Byte R, Byte G, Byte B, Byte A )
{
  return (A<<(3*8)) + (B<<(2*8)) + (G<<(8)) + R ; //LE // works
  // You could also change to bitwise OR, which has lower prec than +
  return A<<(3*8) | B<<(2*8) | G<<(8) | R ; //LE // works
}
Advertisements

One Comment

  1. One more example to confirm my liberal use of ((((()))))


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: