开发者

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).


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜