2

There is a simple algorithm to convert integer values to RGB value of three numbers between 0-255 at integer to rgb. I got the integer number from Android Colors. I even ran:

System.out.println(Color.decode("-16711681"));

and the answer was java.awt.Color[r=0,g=255,b=0], which is expected.

I literally have an issue on step one, -16711681 % 256 is 255, and I expect 0 for the red color. In Java I coded:

System.out.println(-16711681 % 256);

and I get -1, which means I have to add 256 and my red color is 255. Can someone help me?

Community
  • 1
  • 1
smuggledPancakes
  • 9,881
  • 20
  • 74
  • 113
  • 2
    Why are you using decimal literals to represent colors? `0xFF00FF00` is much more clear than `-16711681`. – resueman Aug 28 '14 at 19:04
  • I am sending colors over a websocket and it just seemed simple to get the getRGB() method on my Colors in Java and send them to my client. I was planning on extracted the RGB on the javascript client side. – smuggledPancakes Aug 28 '14 at 19:13

2 Answers2

2

That's because your number is not an ABGR-packed int like your link to gamedev suggests, but an ARGB-packed int.

the Color.decode(int) wants a color in the following format:

0xAARRGGBB

where AA is the transparency, RR is the red, GG is the green, and BB is the blue. When you execute color % 256, that returns the blue (BB) portion of the color.

If we look at the color with Integer.toHexString(-16711681), we get:

 Color:   ff00ffff
(Format:  AARRGGBB)

Which is equivalent to Color[r=0,g=255,b=255]

If you want to read the red value, you need to shift it over first:

(color >> 16) & 0xFF
Darth Android
  • 3,437
  • 18
  • 19
1

Lets say x=-16711681

The Binary value of x is 11111111000000001111111111111111

Integer c = new Integer(-16711681);
System.out.println(Integer.toBinaryString(x));

Now, according to Java Docs to get the Red Value we need to extract 16-23 bits from x

enter image description here


Qn: How do i extract 8 bits from Positions 16-23 out of a 32 bit Integer?

Answer: x = (x >> 16) & 0xFF;


// Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue

Hence, Color.decode("-16711681")); is equivalent to

System.out.println(((-16711681 >> 16) & 0xFF) + ":"
                + ((-16711681 >> 8) & 0xFF) + ":" + ((-16711681 >> 0) & 0xFF));

Output

0:255:255

Note that System.out.println(Color.decode("-16711681")); outputs

java.awt.Color[r=0,g=255,b=255]
Ravi Yenugu
  • 3,895
  • 5
  • 40
  • 58