word color;
crap = ((color & 0xffc0) >> 1) | (color & 0x1f)
I have this shifting code. I have no idea what the purpose is of this code, but I suspect it has something to do with switching between 555 to 565 colors.
How would I create a function that does the exact opposite as the code above? That converts the variable back to the original color number?
Yes, that’s what it’s doing.
colorwill be the 565 representation, andcrapthe corresponding 555 representation.Lets look at what each operation does. I’ll refer to the three fields as
a(5 bits),b(6 bits, transformed to 5) andc(5 bits).(color & 0xffc0)clears the bottom 6 bits of the word, removingcand the least significant bit ofb, preservingaand the most significant 5 bits ofb.>> 1shifts these bits right, so we now havea(5 bits),b(5 bits), and an empty 5-bit field.(color & 0x1f)clears all the bits except for the bottom 5 bits – that is, it preserves ‘c’ and removes the other fields.Finally,
|combines the two values, givingaandbfrom the left-hand side, andcfrom the right-hand side, each in 5 bits.Note that the least significant bit of
bis now zero, whatever it was to start with. That information was lost in the first transformation, and can’t be recovered.