Skip to content

Instantly share code, notes, and snippets.

@wyfinger
Last active May 21, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyfinger/74b040b1f2d966f809fcbca5ca65e606 to your computer and use it in GitHub Desktop.
Save wyfinger/74b040b1f2d966f809fcbca5ca65e606 to your computer and use it in GitHub Desktop.
Convert BGR to RGB without additional variables

So, if you need to convert BGR (as $00BBGGRR) color to RGB (as $00RRGGBB) you can extract individual bytes of color and combine it. But let's do it without additional variables, as brain training.

Var 1: assembler

BSWAP - that's almost what we need. This command swap $AABBCCDD to $DDCCBBAA, later we can shift bytes right.

mov eax,AABBCC
bswap eax     ; EAX = CCBBAA00
shr eax,8     ; EAX = 00CCBBAA

Var 2: byte 3 as temp var

This is a simple but bulky method, code in Pascal.

X := X or (X and $000000FF) shl 24;   // T := b
X := X and $FFFFFF00;                 // b := a
X := X or (X and $00FF0000) shr 16;
X := X and $FF00FFFF;                 // a := T
X := X or (X and $FF000000) shr 8;
X := X and $00FFFFFF;

Var 3: XOR swype

XOR swype is a famous stunt. Let's see (Pascal):

X := $00AABBCC;
X := (X and $FF00FFFF) or (((X and $00FF0000 shr 16) xor (X and $000000FF)) shl 16);  // X := X XOR Y
X := (X and $FFFFFF00) or (((X and $00FF0000 shr 16) xor (X and $000000FF)) shl 0);   // Y := X XOR Y
X := (X and $FF00FFFF) or (((X and $00FF0000 shr 16) xor (X and $000000FF)) shl 16);  // X := X XOR Y

This code was translate by Delphi 7 compiler to this:

mov ebx,AABBCC
mov eax,ebx
and eax,FF0000
shr eax,10
mov edx,ebx
and edx,FF
xor eax,edx
shl eax,10
and ebx,FF00FFFF
or eax,ebx
mov ebx,eax
mov eax,ebx
and eax,FF0000
shr eax,10
mov edx,ebx
and edx,FF
xor eax,edx
and ebx,FFFFFF00
or eax,ebx
mov ebx,eax
mov eax,ebx
and eax,FF0000
shr eax,10
mov edx,ebx
and edx,FF
xor eax,edx
shl eax,10
and ebx,FF00FFFF
or eax,ebx
mov ebx,eax
mov eax,ebx
xor edx,edx

Of course, in the assembler uses additional variables (registers).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment