How to pack ARGB to one integer uniquely?

后端 未结 4 1772
太阳男子
太阳男子 2020-12-05 08:20

I have four integer values (0 - 255) for an ARGB color map.

Now I want to make a unique float or integer of these four integers. Is it possible to do it like the fol

4条回答
  •  北海茫月
    2020-12-05 09:00

    You could do this:

    Assuming a, r, g and b to be of type unsigned char/uint8_t:

    uint32_t color = 0;
    color |= a << 24;
    color |= r << 16;
    color |= g << 8;
    color |= b;
    

    Or more general (a, r, g and b being of any integer type):

    uint32_t color = 0;
    color |= (a & 255) << 24;
    color |= (r & 255) << 16;
    color |= (g & 255) << 8;
    color |= (b & 255);
    

    This will give you a unique integer for every ARGB combination. You can get the values back like this:

    a = (color >> 24) & 255;
    r = (color >> 16) & 255;
    g = (color >> 8) & 255;
    b = color & 255;
    

提交回复
热议问题