How to convert a color integer to a hex String in Android?
Quick solution: convert the color integer to a hex string in Android with the following line:
Let's check this out in an example:
This method fades hexColor
to "#000000"
; essentially translating into Black. The 0xFFFFFF
mask dulls the alpha bits preventing them from making a cameo in your hex color.
Masking alpha and zero-padding
While color integers often carry an alpha channel for transparency, hex strings in #RRGGBB
format aren't as transparent about this fact. 0xFFFFFF
comes in handy by applying a mask to extract only the RGB values, ensuring your hex string is exactly 6-characters long like a VIP entry pass.
What you get is "#0000FF"
, pure blue. Because you know, personality matters!
Anticipating edge cases
While the answer from the Fast answer section generally works well, it doesn't account for:
- Need for alpha in the hex string. In that case, use a
0xFFFFFFFF
mask instead – it's like bringing your entire party! - Negative integers may arise from color definitions. But fear not, your bitwise operation has got your back.
- The output is like shouting hillbillies, all uppercase. If you're more of a lower-case person, just swap out
X
inString.format
withx
.
How does this sorcery work?
-
Masking with bitwise AND: Using
0xFFFFFF
ensures you only carry the RGB values, blocking the alpha channel from photobombing your picture. -
Formatting:
String.format
ties it all with a neat 6 char bow.%06X
ensures your hex string always flaunts the right dimensions. -
Conversion:
Integer.toHexString
also steps up for hex string conversion. But remember, it’s a bit lackadaisical about zero-padding and may include alpha values. -
Validation: Always match your hex string with your expected outcomes. This is like double-checking your tie before that big meeting, especially critical for negative integers or full transparency.
-
Parsing back: If you need a return ticket on this journey,
Integer.parseInt(hexString, 16)
fetches your integer color unlike the dog fetches your frisbee!
Multiple colors: Bulk conversion
Got a color fest? No problemo! Here's your bulk handler:
On the lookout: Common pitfalls and fixes
Alpha channel considerations
When your design is big on transparency and requires alpha intact in the hex string, include it with:
This keeps the alpha channel part of your color talk.
Negative integer values
Got negative vibes from your color integer? Don't worry, that’s more about how alpha is encoded. Negative color integers play nicely with the masking technique we follow. Your hex string has got you covered!
Zero-padding: Consistency is key
Sticking to 6 chars for hex string length is advised as otherwise, it may lead to ugly misunderstandings! Ensure all your hex strings start with zeroes where needed:
Was this article helpful?