How to pack ARGB to one integer uniquely?

后端 未结 4 1775
太阳男子
太阳男子 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 08:53

    You are trying to do a base convert or something of that sort. Anyway the logic is like in base converting. 4 bytes = 32 bit. So 32 bit unsigned integer would do well.

    In this case, you have:

    ARGB = A<<24 + R<<16 + G<<8 + B
    

    it's like this:
    you have 4 bytes of data, meaning

    xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
    

    where X is either 1 or 0 valued bit. You map them like this:

    AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
    

    and then all you have to do is to add them, but before that you shift the bits. You shift the A bits to the left, by 8*3 (to be beyond the limits of R, G and B bits), then shift the R bits by 8*2, and so on.

    You end up adding these 32 bit integers:

    AAAAAAAA 00000000 00000000 00000000
    00000000 RRRRRRRR 00000000 00000000
    00000000 00000000 GGGGGGGG 00000000
    00000000 00000000 00000000 BBBBBBBB
    

    Where A, R, G, B can be either 0 or 1, and represent as a whole, the 8 bit value of the channel. Then you simply add them, and obtain the result. Or as DarkDust wrote, use not the + operator, but instead the | (bitwise or) operator, since it should be faster in this particular case.

提交回复
热议问题