Question:

In getRGB() method why have the bitwise leftshift <<16 and <<8?

by  |  earlier

0 LIKES UnLike

look at the ImutableRGB Class at the java website

http://java.sun.com/docs/books/tutorial/essential/concurrency/imstrat.html

I understand what logical shifts are but why are they used here? The int value returned by the method doesnt make any sense to me. Any ideas?

 Tags:

   Report

2 ANSWERS


  1. I saw your question earlier and it occurred to me I didn&#039;t know the answer either :-)

    So I spent a little while with it, and this is where it got me:

    The program dictates each value is less than or equal to 255. So each value is essentially 8 bits long.

    Let&#039;s say:

    r = 11110000

    g = 00001111

    b = 01010101

    Shift green 8 bits over, it becomes

    0000111100000000

    When you OR that against blue (think of blue as being padded with leading 0s so it&#039;s the same length), it becomes:

    0000111101010101

    And do the same with red. You end up with 24 bits, the first 8 are red, the second 8 are green and the last are blue. Well, obviously, it&#039;s just equivalent to concatenating the binary strings. Solving for them is equivalent to this:

    (rgb &amp; r*2^16) = r*2^16

    (rgb &amp; g*2^16) = b*2^8

    (rgb &amp; b*2^16) = g

    But this often has multiple solutions, and it is the maximum that we are interested in. The obvious way to solve it is with a for loop, start at 255 and work backwards, but that&#039;s inelegant.

    So the elegant way is to notice you can isolate the first 8 bits by left shifting 2^(8)-1 by 16 bits, ANDing that with the RGB triplet, then shifting it back 16 bits.

    The entire triplet is:

    111100000000111101010101

    So,

    111100000000111101010101    AND

    111111110000000000000000

    =

    111100000000000000000000

    Shifting it back over you get 11110000 which is what we started with.

    So, the red is given by (RGB &amp; 255&lt;&lt;16)&gt;&gt;16

    It is therefore obvious that green and blue are given by  (RGB &amp; 255&lt;&lt;8)&gt;&gt;8 and (RGB &amp; 255&lt;&lt;0)&gt;&gt;0 (= RGB&amp;255), respectively.

    hope that helped.


  2. We have binary number system not an ordinary Decimal

    so

    RGB values are in binary form

    R at 2^16

    G at 2^4

    B at 2^0

    so in order to inter shift there values we are using bit shift.

    Hope this will help

    Cheers:)

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.