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
}
One Comment
One more example to confirm my liberal use of ((((()))))