0

Can somebody tell me how to get this ARGB integer values from HTML Hex colors in Java?

It is a 8 digit value which obviously could be negative!?

Thank you very much!

MatrixToImageConfig(-10223615,-1)
neogeoz
  • 109
  • 1
  • 10

1 Answers1

1
public static void main(String[] args) {

    //same colors
    String hex = "#ffffff00";
    Color color = new Color(255,255,255,0);

    //4294967040
    System.out.println(Long.decode(hex));

    //16777215
    System.out.println(toRGBA(hex));

    //16777215
    System.out.println(color.getRGB());

    //-16711681
    System.out.println(toARGB(hex));
}

public static int toRGBA(String nm) {
    Long intval = Long.decode(nm);
    long i = intval.intValue();


    int a = (int) ((i >> 24) & 0xFF);
    int r = (int) ((i >> 16) & 0xFF);
    int g = (int) ((i >> 8) & 0xFF);
    int b = (int) (i & 0xFF);

    return ((b & 0xFF) << 24) |
            ((g & 0xFF) << 16) |
            ((r & 0xFF) << 8)  |
            ((a & 0xFF) << 0);
}

public static int toARGB(String nm) {
    Long intval = Long.decode(nm);
    long i = intval.intValue();


    int a = (int) ((i >> 24) & 0xFF);
    int r = (int) ((i >> 16) & 0xFF);
    int g = (int) ((i >> 8) & 0xFF);
    int b = (int) (i & 0xFF);

    return ((a & 0xFF) << 24) |
            ((b & 0xFF) << 16) |
            ((g & 0xFF) << 8)  |
            ((r & 0xFF) << 0);
}
  • If neogeoz only needs an integer value, what is the benefit of splitting it up into its ARGB components? Why not just `return Integer.decode(nm);`? – VGR Jul 14 '19 at 21:18
  • @VGR Integer.decode(nm); decodes the hex value to the decimal value, but thats not the same how rgba value – Patrick Zamarian Jul 14 '19 at 21:34
  • 1
    I’m pretty sure it is. Try `System.out.printf("%08x%n", Integer.decode(nm));` and see for yourself. – VGR Jul 14 '19 at 21:39
  • I edited the post for a little demonstration and I found mistakes from me – Patrick Zamarian Jul 14 '19 at 22:42
  • What does your method accomplish that `Long.decode` does not? – VGR Jul 14 '19 at 22:45
  • watch difference? – Patrick Zamarian Jul 14 '19 at 23:01
  • Thank you both very much. Both answers helped me to understand the problem better. In the end I was able to use ZamarianPatrick's solution. Of course I still tested VGR's solution. But I got a NumberExeption. Maybe it was because the alpha value can cause negative numbers...? – neogeoz Jul 15 '19 at 15:15