Search code examples
javaandroidstringcolorshex

How to convert a color integer to a hex String in Android?


I have an integer that was generated from an android.graphics.Color.
It has a value of -16776961. How do I convert it into a hex string with the format #RRGGBB?

Simply put: I would like to output #0000FF from -16776961.

Note: I don't want the output to contain alpha and I have also tried this example with no success.


Solution

  • The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):

    String hexColor = String.format("#%06X", (0xFFFFFF & intColor));