GayLord
GayLord

Reputation: 135

What are "&" and "|" used for in this color generation code?

Just stumbled upon the 2d game development video series on YouTube by designsbyzephy, and decided learning and understanding the code from the video will be my next Java learning venture.

The biggest obstacle is trying to decipher the code myself because the video maker has an incredibly newbie unfriendly approach to explaining everything.

So here's my question and the video

video: http://www.youtube.com/watch?v=7eotyB7oNHE

at 5:31, he types in the code

int index = 0;
    for (int r = 0; r < 6; r++){
        for (int g = 0; g < 6; g++){
            for (int b = 0; b < 6; b++){

                int rr = (r * 255/5);
                int gg = (g * 255/5);
                int bb = (b * 255/5);

                colors[index++] = rr << 16 | gg << 8 | bb;
            }
        }
    }
colors[index++] = rr << 16 | gg << 8 | bb;

From my understanding he's filling the array with all combinations created by 6 shades for each color, but what I don't get is what the | symbol stands for. He mentions in the video that he talks about it in the previous videos, but he doesn't, I checked, and I am sure he's mistaking his explanation on & with |, because he does touch upon the & operation a little way, but never mentions | in any of his previous videos. Another thing I don't get is why we're shifting the colors. He explains it in the video, but it still doesn't make sense to me. Basically all he says is we shift it because bb, gg, and rr all have 2&8 bits of data in it, but that doesn't suffice as an explanation for me. I need to know why we're doing it, why do we need to shift to left just because the bb, gg, rr colors have 2^8 bits of data in it, and what does having 2^8 bits of data mean in the first place?

Upvotes: 3

Views: 338

Answers (1)

HectorLector
HectorLector

Reputation: 1911

The | in java is the bitwise or operator: Bitwise operations Without watching the whole video, I guess what he is trying to do is put all color values (RGB) into one 32Bit integer. Since rr,gg,bb can only have values from 0-255, which only need 8bits, he can put them into just one variable by using shift and or operations. For example:

rr:       00000000 00000000 00000000 10101010
rr<<16:   00000000 10101010 00000000 00000000

gg:       00000000 00000000 00000000 11110000
gg<<8:    00000000 00000000 11110000 00000000

bb:       00000000 00000000 00000000 00001111

value = rr << 16 | gg << 8 | bb 

rr<<16:   00000000 10101010 00000000 00000000
gg<<8:    00000000 00000000 11110000 00000000
bb:       00000000 00000000 00000000 00001111

value:    00000000 10101010 11110000 00001111
                      ^        ^        ^
                      rr       gg       bb

So now we have all three color values in one single integer variable.

Upvotes: 9

Related Questions