reload reload - 1 month ago 20
Java Question

Java single int colors

I can't understend, how to extract rgb colors from int like


1751661885


And


2053651730


I'm currently digging in Minicraft (not minecraft) source code.
For example: here is line from
com.mojang.ld22.level.tile.DirtTile.java
:

int col = Color.get(level.dirtColor, level.dirtColor,
level.dirtColor - 111, level.dirtColor - 111);


What happens here? Is there a way to convert those colors back to rgb?
And one more question: How does author mix two colors like so:

enter image description here

Those grass and stone tiles are drawn in gray colors,:

enter image description here

Okey, he applies color filter to texture. But on the same tile, here is some brown between rocks and grass.. How? I have no ideas..

Answer

Java ints have 32 bits; so you can pack 4 8-bit numbers into a single int. Java encodes colors using ARGB encoding:

  • The 8 most-significant bits are the alpha
  • The 8 next-significant bits are the red
  • The 8 next-significant bits are the green
  • The 8 least-significant bits are the blue.

You can unpack these using basic bit manipulation:

int color = 1751661885;
System.out.printf("Packed color (dec): %d%n", color);
System.out.printf("Packed color (hex): %08X%n", color);

int alpha = (color >> 24) & 0xFF;
int red = (color >> 16) & 0xFF;
int green = (color >> 8) & 0xFF;
int blue = (color >> 0) & 0xFF;

System.out.printf("Hex: a=%02X r=%02X g=%02X b=%02X%n", alpha, red, green, blue);
System.out.printf("Dec: a=%d r=%d g=%d b=%d%n", alpha, red, green, blue);

Output:

Packed color (dec): 1751661885
Packed color (hex): 68683D3D
Hex: a=68 r=68 g=3D b=3D
Dec: a=104 r=104 g=61 b=61

Ideone demo.