Composition of multiple integers into one integer & vice versa

194 Views Asked by At

Here's the context :

Images are made up of Pixels, which is basically an [R,G,B] array/list with R, G & B, being integers representing the colors Red, Green & Blue. So an image with MxN dimensions will have MxN [R,G,B] arrays/lists representing MxN Pixels.

I wanted to convert each of the [R,G,B] array/list into a single integer, in such a way that the single integer can be later decomposed into respective R, G & B values. Converting [R, G, B] array/list forming a pixel, into a single integer would convert the Image into matrix, on which matrix operations can be performed & later the respective elements of matrix can be decomposed into [R, G, B] values.

Is it possible through some form of weighted measure? e.g. aR + bG + cB = x

1

There are 1 best solutions below

0
On BEST ANSWER

Note each $R$, $G$ and $B$ value in standard $RGB$ format is between $0$ and $255$, inclusive. Thus, each value can fit in one $8$-bit byte and you can combine them into a single $4$ byte integer so the $B$ value is in the lowest byte, then $G$ is in the second byte and $R$ is in the third byte. This can be done using

$$(2^{16})R + (2^8)G + B = x \tag{1}\label{eq1A}$$

Later, to decompose, you can just take the bits from each byte and shift then down, with this shift being $0$ bits for $B$ (i.e., no shift), $8$ bits for $G$ and $16$ bits for $R$. Most computer languages (e.g., C, C++, C#, Python, Java, etc.) have built-in functionality to do this directly. However, if your language doesn't provide this, it's not very difficult to implement using other basic code.