markand
markand

Reputation: 525

Integer to store color in C, endian dependent

I have a question about endianness, I like to store my colors in HTML format (RGB like #aabbcc).

I always use 0xaabbcc in my code to store the color, and then to extract the red, green and blue colors I apply masks like this:

int color = 0xaabbcc;
int r = color & 0xff0000;
int g = color & 0x00ff00;
int b = color & 0x0000ff;

This works well, but I have not tested under a big endian machine, will the result be the same?

I must see that SDL checks the endian for creating surfaces as in the example of man SDL_CreateRGBSurface:

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
   rmask = 0xff000000;
   gmask = 0x00ff0000;
   bmask = 0x0000ff00;
   amask = 0x000000ff;
#else
   rmask = 0x000000ff;
   gmask = 0x0000ff00;
   bmask = 0x00ff0000;
   amask = 0xff000000;
#endif

   surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32,
                                  rmask, gmask, bmask, amask);

Upvotes: 0

Views: 928

Answers (3)

tomlogic
tomlogic

Reputation: 11694

Unless you're serializing the data in some way (saving to disk, sending over a network link) or accessing it as something other than an integer (as in Richard J. Ross III's answer mentioning a char *), it doesn't matter. Your variables and your masks have the same byte order.

Upvotes: 0

jncraton
jncraton

Reputation: 9132

As long as you are dealing with the actual individual bits, endianness does not matter. You run into issues when dealing with the numeric values that the bits represent. You are simply setting a value, and then using a mask to read it back, so you should not have any problems.

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55563

Yes. Bitmasks are independent of endianness. The only place where endianness would be an issue would be if you were casting it to a byte array (or, in c, a char *), in which case the endianness would matter.

Also ensure that sizeof(int) > 3 before using this code!

Upvotes: 2

Related Questions