Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pack ARGB to one integer uniquely?

Tags:

rgb

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?

like image 524
Roby Avatar asked Sep 09 '11 07:09

Roby


2 Answers

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;
like image 65
DarkDust Avatar answered Oct 06 '22 09:10

DarkDust


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.

like image 32
Alex Avatar answered Oct 06 '22 07:10

Alex