Click to See Complete Forum and Search --> : Please explain the << in this code ???
int w = 100;
int h = 100;
int pix[] = new int[w * h];
int index = 0;
for (int y = 0; y < h; y++) {
int red = (y * 255) / (h - 1);
for (int x = 0; x < w; x++) {
int blue = (x * 255) / (w - 1);
pix[index++] = (255 << 24) | (red << 16) | blue;
}
}
Image img = createImage(new MemoryImageSource(w, h, pix, 0, w));
DHunter21
May 12th, 2000, 02:44 PM
<< is a shift bits to the left operator. An RGB value can be stored in 3 bytes (or 4 if you are using an alpha channel), one for each color. So one "long" variable can contain the rgb number. By using the << operator you shift the binary number by a certain amout of bits:
For example
int a = 0xFA; // == 11111010
int b = a<<2; // == 1111101000
int c = a>>2; // == 111110
So in your example you are saying shift 255 (0xFF) by 24 bits and add red shifted by 16 bits and then add blue. The same task could be accomplished by using
pix[++index] = 0xFF0000 + red*256 + blue;
Rogersssk
November 16th, 2000, 03:26 PM
I think the last statement should be
pix[++index] = 0xFF000000 + red*256*256 + blue;
Roger
weaver
November 16th, 2000, 07:01 PM
True that you can replace the <<, however, when multiplying a number by a multiple of 2, using the << operator is much faster, if you are concerned with optimization. It does sacrifice readability though.
-------------------------------------------
weaver
icq# 97002680
Please rate this post.
http://www14.brinkster.com/tsryan
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.