0

I am trying to make coder/decoder in Java so I could store RGB value in Hex format. I have coder like this:

System.out.println("#" + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue()));

and decoder like this:

System.out.println(decodeColor("#"
    + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue())));

Implementation of decodeColor() function is:

private RGB decodeColor(String attribute) {
    Integer intval = Integer.decode(attribute);
    int i = intval.intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}

When I run test program, I get this output:

  • initial values are new RGB(15, 255, 45)

<\label ... color="#fff2d">...</label>

RGB {15, 255, 45}

  • initial values are RGB(15, 0, 45)

<\label ... color="#f02d">...</label>

RGB {0, 240, 45}

So, in some cases it returns correct result, but in other its totally messed up. Why is that?

miller
  • 1,636
  • 3
  • 26
  • 55
  • [This](https://www.google.co.in/?q=java+rgb+to+hex) might help. Also refer to related questions on the right. – devnull Sep 20 '13 at 10:22
  • These two discussions could be helpful: http://stackoverflow.com/questions/3607858/how-to-convert-a-rgb-color-value-to-an-hexadecimal-value-in-java and http://stackoverflow.com/questions/4129666/how-to-convert-hex-to-rgb – Ernestas Kardzys Sep 20 '13 at 10:30

2 Answers2

3

Because #rrggbb always requires 2 hex digits per color component.

String s = String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue());

Color c = Color.decode(s);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0
Integer intval = Integer.decode(attribute);

Here, the string attribute starts with a #, but it should start with 0x.

private RGB decodeColor(String attribute) {
    String hexValue = attribute.replace("#", "0x");

    int i = Integer.decode(hexValue).intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}
Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50