Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

rgb - How to pack ARGB to one integer uniquely?

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 following?

sum  = 4 * 255 + A;
sum += 3 * 255 + R;
sum += 2 * 255 + G;
sum += 1 * 255 + B;

Is the value really unique?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...