CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Guest

    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 &lt; h; y++) {
    int red = (y * 255) / (h - 1);
    for (int x = 0; x &lt; w; x++) {
    int blue = (x * 255) / (w - 1);
    pix[index++] = (255 &lt;&lt; 24) | (red &lt;&lt; 16) | blue;
    }
    }
    Image img = createImage(new MemoryImageSource(w, h, pix, 0, w));





  2. #2
    Join Date
    Aug 1999
    Location
    San Diego
    Posts
    155

    Re: Please explain the << in this code ???

    &lt;&lt; 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 &lt;&lt; operator you shift the binary number by a certain amout of bits:

    For example
    int a = 0xFA; // == 11111010
    int b = a&lt;&lt;2; // == 1111101000
    int c = a&gt;&gt;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;


  3. #3
    Join Date
    Aug 2000
    Location
    Texas, U.S
    Posts
    28

    Re: Please explain the << in this code ???

    I think the last statement should be
    pix[++index] = 0xFF000000 + red*256*256 + blue;

    Roger



  4. #4
    Join Date
    Jan 2000
    Location
    Canada
    Posts
    249

    Re: Please explain the << in this code ???

    True that you can replace the &lt;&lt;, however, when multiplying a number by a multiple of 2, using the &lt;&lt; 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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured