Author Topic: Macro to Convert XRGB to XBGR  (Read 1180 times)

satpro

  • Member
  • **
  • Posts: 116
Macro to Convert XRGB to XBGR
« on: July 03, 2015, 12:01:52 AM »
In DirectX a common color format is X8R8G8B8.  To combine GDI calls with DirectX, in which the RGB byte order is reversed to BGR for Windows to something like X8B8G8R8, a byte order shift is needed.  If you study C/C++ conversion techniques listed on the Internet (with all the byte shifting, <<, >>, etc.) it can really make the head spin.  In reality the solution is simple and short in assembly language.  It's only a matter of reversing the byte order with BSWAP while making sure the X8 byte stays in bits 24-31.  Using a macro makes it slightly easier on the eyes.

Although not much, it works well for 32-bit code.  Maybe someone can expand on it and post a more robust x86 or even a 64-bit solution suitable for general inclusion.  Maybe rename it.  :biggrin:

It goes like this:

Code: [Select]
#IFNDEF rgb2bgrR            // using a pre-loaded register
  rgb2bgrR(regx86) MACRO    // XRGB is loaded in a register, such as eax, etc.
    bswap regx86
    ror regx86, 8           // comes out formatted as XBGR
  ENDM
#ENDIF

#IFNDEF rgb2bgrC            // using a constant (an immediate) instead
  rgb2bgrC(value) MACRO     // XRGB is loaded as a numerical value, such as 0xFFB612, or defined constant, such as PackersGold
    mov eax, value
    bswap eax
    ror eax, 8              // comes out as 0x12B6FF
  ENDM
#ENDIF



I use it like this:

Code: [Select]
mov ecx, PackersGold        // if you're from where I grew up, this is one of your two favorite colors!
rgb2bgrR(ecx)               // use any general purpose register here, result returned in that register

or...

rgb2bgrC(PackersGold)       // default output is in EAX as defined above

Any general x86 register (if using rgb2bgrR, defaults to EAX if rgb2bgrC is used) will then contain the color converted and suitable for a GDI call.  Hope you can use this and please excuse if it seems remedial.