## Turning a 32-bit variable into 4 8-bit ones

Moderator
Posts: 683
Joined: 2002.11
Post: #1
OK, here is the BlitzMax command I am trying to use (for your reference):

Returns: A 32 bit pixel value
The returned 32 bit value contains the following components:
bits 24-31 : pixel alpha
bits 16-23 : pixel red
bits 8-15 : pixel green
bits 0-7 : pixel blue

How do you suggest I split these up? I really have no clue.

This is one of the few times where I actually miss METAL. You could use more than 2 buffers, control which buffer you were writing to without showing the other one on the screen, and "getpixel" was dead easy

My web site - Games, music, Python stuff
Member
Posts: 257
Joined: 2004.06
Post: #2
diordna Wrote:OK, here is the BlitzMax command I am trying to use (for your reference):

Returns: A 32 bit pixel value
The returned 32 bit value contains the following components:
bits 24-31 : pixel alpha
bits 16-23 : pixel red
bits 8-15 : pixel green
bits 0-7 : pixel blue

How do you suggest I split these up? I really have no clue.

Does BlitzMax have bit-wise operators such as bit-shifting (>> and <<) and masking (like & and |). Because if you do, you can do something like:

Code:
UInt32 pixel;
UInt8 alpha, red, green, blue;

blue = pixel & 0x000000ff;
green = (pixel >> 8) & 0x000000ff;
red = (pixel >> 16) & 0x000000ff;
alpha = (pixel >> 24) & & 0x000000ff;

Erg. Hopefully that's right. I haven't done that in a while. The idea is basically to use a bit-wise AND to get the last 8 bits of the value and using the bit-shifts to move the other 8bit values down to the end which are then masked out as well.

The brains and fingers behind Malarkey Software (plus caretaker of the world's two brattiest felines).
Moderator
Posts: 683
Joined: 2002.11
Post: #3
Why yes...I just found the shift operators. Thank you.

My web site - Games, music, Python stuff
Apprentice
Posts: 5
Joined: 2009.01
Post: #4
An even better way would be to use a union for your colors.

Code:
typedef union {
UInt32 rgba;
struct {
UInt8 r,g,b,a;
} comp;
} color;

Then you can access the components directly without any 'bit-hacks' and at the same time have access to the packed 32-bit color.

Code:
color c;
UInt8 blueComponent = c.comp.b;
...
UInt32 newColor = c.rgba;

Both versions compile to exactly the same assembly code, so it's just a matter of taste I guess. I prefer readable code.

.johan
Member
Posts: 469
Joined: 2002.10
Post: #5
Even easier is using an anonymous struct to hold the components.

Code:
typedef union {
UInt32 rgba;
struct {
UInt8 r,g,b,a;
};
} FourBytePixel;

FourBytePixel px;
px.rgba = ...
px.r = ...
px.g = ...
px.b = ...
px.a = ...
etc

---Kelvin--
15.4" MacBook Pro revA
1.83GHz/2GB/250GB