algorithm to convert integer to 3 variables (rgb)
I try to store integer (real numbers) values into pixel data. The only way my api can store pixel data are RGB Colors. The idea behind it is, to store a large amount of vertices into the vram, rather than into the ram and compare them. A RBG Color is created by rgb(r, g, b), where r, g and b can have 256 different values (0 - 255).
So i could theoretically store 256^3 values. The integer could be greater than that, but i dont need that high numbers.
My goal is to store for example:
integer 1 = rgb(1, 0, 0);
integer 2 = rgb(0, 1, 0);
[...]
My math understanding has slightly decreased the years after graduating, but im aware, that if im looping first through red, then green and at the end blue, i could only use 256*3 numbers.
Therefore my question is: how could i convert (or split) any real number below 256^3 into 3 variables (r, g, b).
No special languague syntax is required, but im happy with c or java syntax
$\endgroup$ 13 Answers
$\begingroup$I think what you're looking for is the same as hex valued colors. These are of the form:
$$ X_6X_5X_4X_3X_2X_1 $$
where $X_2X_1$ is a hex valued number representing the blue value, $X_4X_3$ is a hex valued number representing the green value, and $X_6X_5$ is a hex valued number representing the red value. All you have to do is represent your integer as:
C = 256^2* R + 256* G + B;
then you have that
R = C/(256^2);
G = (C/256) % 256;
B = C%256;
The accepted answer I saw is incorrect. Again, we write $$C = 256^2 R + 256 G + B$$ for positive integers $R,G,B < 256$. We clearly see that $B\equiv C \mod{256}$, or in pseudocodeB = C % 256. That part was correct.
Now we just subtract $B$ from $C$ and repeat the process.
\begin{align} & C - B = 256^2 R + 256 G \\ \implies & \frac{C-B}{256} = 256 R + G \\ \implies & G \equiv \frac{C-B}{256} \mod{256} \end{align}
And again:
\begin{align} & \frac{C-B}{256} - G = 256 R \\ \implies & R = \frac{C-B}{256^2} - \frac{G}{256} \,. \end{align}
In conclusion, we have
B = C % 256
G = ((C-B)/256) % 256
R = ((C-B)/256**2) - G/256We could also do this algorithmically, not that it's efficient or useful:
# Assuming that C is a positive integer less than or equal to 0xffffff
x = C
# Repeatedly subtract 1 from x = C until x is a multiple of 0x10000
while x % 0x10000 != 0: x -= 1
# We have our red component
R = int(x / 0x10000)
# Repeat for the green component
y = c - x
while y % 0x100 != 0: y -= 1
# We have our green component
G = int(y / 0x100)
# And finally our blue component
B = C - x - y # == C - (x + y) $\endgroup$ $\begingroup$ There is a typo in your formula for the green component. Corrected:
R = C/(256^2);
G = (C/256) % 256;
B = C%256;