How to pack ARGB to one integer uniquely?

后端 未结 4 1774
太阳男子
太阳男子 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:10

    Not quite. You need to use bit-shifting and not simple multiplication.

    Each value in your color map is 8 bytes long, correct? So in order for the resulting number to be unique, it must string them all together, for a total of 8*4=32 bits. Look at the following:

    You want to take:

    AAAAAAAA
    RRRRRRRR
    GGGGGGGG
    BBBBBBBB
    

    and make it look like:

    AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB
    

    This means you have to add the following together:

    AAAAAAAA000000000000000000000000
            RRRRRRRR0000000000000000
                    GGGGGGGG00000000
                            BBBBBBBB
    --------------------------------
    AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB
    

    We accomplish this by bit-shifting to the left. Taking A and shifting 24 bits to the left will produce AAAAAAAA followed by 24 0 bits, just like we want. Following that logic, you will want to do:

    sum = A << 24 + R << 16 + G << 8 + B;
    

    To illustrate why what you suggest (using multiplication) does not work, what you suggest results in the following binary numbers, which you can see overlap:

    255 * 1 = 0011111111
    255 * 2 = 0111111110
    255 * 3 = 1011111101
    255 * 4 = 1111111100
    

    Furthermore, simply adding your A, R, G, B values to the resulting number will always be constant. Simplifying your math above we get:

    4 * 255 + A + 3 * 255 + R + 2 * 255 + G + 1 * 255 + B
    255 * (4 + 3 + 2 + 1) + A + R + G + B
    255 * (10) + A + R + G + B
    2550 + A + R + G + B
    

    Oops.

提交回复
热议问题