Precursor
Precursor

Reputation: 642

C++ Pack RGBA to unsigned int

With the following class, assuming RGBA are all between 0-255

class Color {
    public:
        short int r;
        short int g;
        short int b;
        short int a;

I've seen libraries such as the aging GD library using bitshifting and &, like

 ((r & 0x7F000000) << 24) & ...

but I'm concerned this might be slow, and I'd prefer a more common approach. Anyone know how I could pack the RGBA values into an unsigned int without using excessive bitwise operators(the GD approach uses about 6-8 bitshift per byte).

Upvotes: 0

Views: 3460

Answers (4)

Patrick87
Patrick87

Reputation: 28292

If you store the rgba values in the class in the appropriate order, just interpret the class instance as an unsigned int. No time. It's done all the time in C.

See Mark's answer for more detail.

Upvotes: 2

MSN
MSN

Reputation: 54554

Bit shifts of a constant amount are not slow. Masking is generally not slow.

On some processors, variable shifts are slow. But packing RGBA colors into an integer does not involve variable shifts, so it tends to be not slow.

Upvotes: 2

Michael Dorgan
Michael Dorgan

Reputation: 12515

Bitwise operators aren't really "slow". Actually, they are usually some of the fastest operations a CPU can execute. Heck ARM gives you shifts for free most of the time. When it comes down to it, if you want to pack vars into a smaller space safely (making sure of no bit overflow), you need to use the bitwise functions. Even bitfields internally default to them.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308121

The easiest way is to redefine your Color class to hold unsigned char rather than short, and make sure they're in the correct order for the endianness of your processor. Then make it a union with a 32-bit integer type.

Upvotes: 2

Related Questions