How to convert a color integer to a hex String in Android?
Asked Answered
D

14

244

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.

Diapositive answered 30/6, 2011 at 19:12 Comment(4)
What are you trying to set the hex color on? I think there's a different answer hereAirdrop
@Airdrop Am exporting the color to an external application. The colour needs to be in this format #RRGGBBDiapositive
So what's wrong with developer.android.com/reference/android/content/res/… ? You'll have to paste the url or scroll to getColor(int)Airdrop
Am getting the raw integers. The values are not from a resource ow widgetDiapositive
R
567

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));
Radiosensitive answered 30/6, 2011 at 19:56 Comment(14)
This worked perfectly, thank you! Easier and more accurate than trying to use substring on Integer.toHexString().Erie
How would it be if I wanted it the other way round, please?Internationalist
I've just realized there is Color.parseColor(String hex) method which does exactly what I'm asking for.Internationalist
@anoniim you're awesome :) was having trouble with ColorDrawable in Android.Trimming
If RED=0 and GREEN=131 and BLUE=146 the result I get is 02004 instead of 008392. What am I doing wrong?Ebarta
SiKini8, this piece of code doesn't take individual r, g, and b parameters, but a single int. What are you passing for intColor?Radiosensitive
int intColor = getResources().getColor(R.color.yourColor);Bullough
How to do reverse of that? For example How to convert hex colour to integer?Rhoades
int colorInt = 0xff000000 | Integer.parseInt(hexString, 16);Radiosensitive
Don't use this answer if your color uses alpha. You'll lose it.Tortilla
@Simon, to make this alpha-ready just remove the mask and change 6 to 8. Note that OP asked for dismissing alpha.Beals
This code does not work in Kotlin. Could you post a working Kotlin version pls? :-)Gerlac
exactly what I was looking forHaimes
@voghDev, for Kotlin change the & to and. For example, val hex = String.format("#%08X", (0xFFFFFF and color))Sst
F
61

Try Integer.toHexString()

Source: In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

Figurant answered 30/6, 2011 at 19:17 Comment(4)
This answer retains the alpha of the colorDiapositive
Well, if you want to get rid of the alpha, just create a bit mask for it: Integer.toHexString(value & 0x00FFFFFF)Figurant
Java int type is 4 bytes long. According to android.graphics.Color's documentation, the leftest byte is the alpha channel. By using a bit wise AND operation with the value 0x00FFFFFF, you essentially clears the leftest byte (alpha channel) to 0. When used with Integer.toHexString, it'll just leave the rest of the 3 bytes in String. All non-significant digits will be dropped from the call, so if you want the leading zeroes, you may have to prepend that in yourself.Figurant
Doesn't work for 0x000000FF, or 0xFF0000FF if you remove the alpha.Beals
D
30

I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.

Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);

Note only use this code if you are sure that removing the alpha would not affect anything.

Diapositive answered 1/7, 2011 at 6:39 Comment(2)
If you send 0x00FFFFFF through this it'll crash Color.parseColor.Beals
@Beals use Color.TRANSPARENT for such casePilcomayo
T
18

You can use this for color without alpha:

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

or this with alpha:

String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));
Theisen answered 15/8, 2020 at 17:14 Comment(0)
H
14

Integer value of ARGB color to hexadecimal string:

String hex = Integer.toHexString(color); // example for green color FF00FF00

Hexadecimal string to integer value of ARGB color:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);
Hainan answered 4/1, 2018 at 14:21 Comment(0)
I
10

Here is what i did

 int color=//your color
 Integer.toHexString(color).toUpperCase();//upercase with alpha
 Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha

Thanks guys you answers did the thing

Imaginary answered 17/12, 2012 at 17:53 Comment(4)
The first variant doesn't work for 0x00FFFFFF -> "FFFFFF" (no alpha). The second variant doesn't work for 0x00000FFF -> "F" (missing bits).Beals
@Beals did you a solution that reliably works for colors with alpha channel?Zilla
@Zilla The top answer's variant should: String.format("#%08X", intColor)Beals
@Beals Ah, just saw your comment under the top answer. Thanks!Zilla
T
4

With this method Integer.toHexString, you can have an Unknown color exception for some colors when using Color.parseColor.

And with this method String.format("#%06X", (0xFFFFFF & intColor)), you'll lose alpha value.

So I recommend this method:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }
Tortilla answered 27/9, 2017 at 21:25 Comment(0)
K
3

If you use Integer.toHexString you will end-up with missed zeros when you convert colors like 0xFF000123. Here is my kotlin based solution which doesn't require neither android specific classes nor java. So you could use it in multiplatform project as well:

    fun Int.toRgbString(): String =
        "#${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    fun Int.toArgbString(): String =
        "#${alpha.toStringComponent()}${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    private fun Int.toStringComponent(): String =
        this.toString(16).let { if (it.length == 1) "0${it}" else it }

    inline val Int.alpha: Int
        get() = (this shr 24) and 0xFF

    inline val Int.red: Int
        get() = (this shr 16) and 0xFF

    inline val Int.green: Int
        get() = (this shr 8) and 0xFF

    inline val Int.blue: Int
        get() = this and 0xFF
Krebs answered 5/6, 2020 at 16:59 Comment(0)
M
1

Simon's solution works well, alpha supported and color cases with a leading "zero" values in R, G, B, A, hex are not being ignored. A slightly modified version for java Color to hex String conversion is:

    public static String ColorToHex (Color color) {
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();
    int alpha = color.getAlpha(); 

    String redHex = To00Hex(red);
    String greenHex = To00Hex(green);
    String blueHex = To00Hex(blue);
    String alphaHex = To00Hex(alpha);

    // hexBinary value: RRGGBBAA
    StringBuilder str = new StringBuilder("#");
    str.append(redHex);
    str.append(greenHex);
    str.append(blueHex);
    str.append(alphaHex);

    return str.toString();
}

private static String To00Hex(int value) {
    String hex = "00".concat(Integer.toHexString(value));
    hex=hex.toUpperCase();
    return hex.substring(hex.length()-2, hex.length());
} 

another solution could be:

public static String rgbToHex (Color color) {

   String hex = String.format("#%02x%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() );
   hex=hex.toUpperCase();
       return hex;
}
Madonna answered 5/3, 2022 at 2:37 Comment(0)
R
0
String int2string = Integer.toHexString(INTEGERColor); //to ARGB
String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color
Riane answered 15/1, 2017 at 11:57 Comment(0)
V
0

use this way in Koltin

var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"
Valenti answered 18/4, 2021 at 17:43 Comment(0)
E
0

Fixing alpha issue in Color picker libraries.

if you get an integer value in return when you pick color first convert it into the hex color.

    String hexVal = String.format("#%06X", (0xFFFFFFFF & 
    color)).toUpperCase();

    int length=hexVal.length();
    String withoutHash=hexVal.substring(1,length);


    while (withoutHash.length()<=7)
    {

        withoutHash="0"+withoutHash;

    }
    hexVal ="#"+withoutHash;
Emmott answered 1/7, 2021 at 16:51 Comment(0)
Q
0

Here is the new Kotlin 1.9.0 standard library HexFormat:
(don't forget to add @OptIn(ExperimentalStdlibApi::class) where needed)

val myHexFormat = HexFormat {
    upperCase = false
    number.prefix = "#"
    number.removeLeadingZeros = true
}
val myInt = 0xb40e89
myInt.toHexString(myHexFormat)         // #b40e89

You could also use the Kotlin predefined HexFormats:

val myInt = 0xb40e89
myInt.toHexString(HexFormat.Default)   // 00b40e89
myInt.toHexString(HexFormat.UpperCase) // 00B40E89

To exclude the alpha from an ARGB integer, do this workaround:

(myInt and 0xFFFFFF).toHexString(myHexFormat)

And vote for this issue: Cannot ignore alpha when formatting with HexFormat

Quiet answered 28/7, 2023 at 10:8 Comment(0)
C
0

Kotlin way (with alpha removed):

val str = color.toArgb().toHexString(HexFormat.Default).takeLast(6)

If you actually want to display the alpha component, remove the takeLast() call:

val str = color.toArgb().toHexString(HexFormat.Default)
Colley answered 11/4 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.