Friday, April 14, 2017

RGB Convert- Bitshift - SHR


If you want to convert an hexadecimal into its RGB components using a very fast technique then you should try Logical Shift. A logical shift is a bitwise operation that shifts all the bits of its operand. The two base variants are the logical left shift (SHL) and the logical right shift (SHR). They come from the good old days of Assembler.

So, how does it work? In our example, we will obtain the components or channels of the following hexadecimal value.

#ff0cf0 base 16

We want to get from 16714992 base 10 to:
red=255 ;  green=12 ; blue=240.




Note: To simplify we will just use 16 bytes and not RGBA of 24 bytes that includes the alpha (transparency) component. 
<Sample code in Freepascal:>

Program Convert;
var
  r,g,b: longint;

procedure RGB_Convert(RGB:longint; var r,g,b:longint); 

{Byvalue reference (var r,g,b). That means that we pass variables to the functions no values.}

begin
   R := (RGB shr 16);
   G := (RGB shr 8) and 255;
   B := (RGB) and 255;
end;

Begin
  RGB_Convert($ff0cf0,r,g,b);
End.

No comments:

Post a Comment