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?
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:
and make it look like:
This means you have to add the following together:
We accomplish this by bit-shifting to the left. Taking
A
and shifting 24 bits to the left will produceAAAAAAAA
followed by 240
bits, just like we want. Following that logic, you will want to do: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:
Furthermore, simply adding your A, R, G, B values to the resulting number will always be constant. Simplifying your math above we get:
Oops.
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:
it's like this:
you have 4 bytes of data, meaning
where X is either 1 or 0 valued bit. You map them like this:
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 ofR
,G
andB
bits), then shift theR
bits by 8*2, and so on.You end up adding these 32 bit integers:
Where
A
,R
,G
,B
can be either0
or1
, 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.You could do this:
Assuming
a
,r
,g
andb
to be of typeunsigned char
/uint8_t
:Or more general (
a
,r
,g
andb
being of any integer type):This will give you a unique integer for every ARGB combination. You can get the values back like this: