Parse Hex Color Code to ARGB Integer
StringsAuto-graded · 24 test casesLast updated
Parse a hex color string (6 or 8 characters) into a 32-bit ARGB packed integer, returning a fallback on invalid input.
In application UI frameworks, dynamic theme properties and color themes are often represented as hex strings.
Write a function parse_hex_color that converts a hex color string into a 32-bit packed ARGB integer (where 0xAARRGGBB represents alpha, red, green, and blue byte components).
Processing Rules
-
Input Normalization:
- First, trim any leading and trailing whitespace from the input string.
- Next, if the trimmed string starts with a single
#character, remove it.
-
Parsing Rules:
- The value is parsed in hexadecimal (base 16) using standard string-to-integer conversion logic (specifically matching Python's
int(value, 16)behavior). - If the stripped string length is exactly 6 characters (
RRGGBB), set the highest byte (alpha) to0xFFby performing a bitwise OR with0xFF000000(i.e.0xFF000000 | parsed). - If the stripped string length is exactly 8 characters (
AARRGGBB), return the parsed base-16 integer directly.
- The value is parsed in hexadecimal (base 16) using standard string-to-integer conversion logic (specifically matching Python's
-
Fallback Output (
0xFF808080): Return0xFF808080(4286578816 in decimal) if any of the following occur:- The input
hex_stringis not a string (e.g.Noneor an integer). - After stripping whitespace and at most one leading
#, the resulting string length is not equal to 6 or 8. - Base-16 parsing fails or raises an error (such as when non-hex characters like
"Z"are present).
- The input
Constraints
- The input
hex_stringcan be of any type, includingNone. - Output must be an integer.
Examples
Example 1
Input: parse_hex_color('#00C805')
Output: 4278241285
Example 2
Input: parse_hex_color('#AARRGGBB')
Output: 4286611584
Example 3
Input: parse_hex_color('#80FF5000')
Output: 2164215808
Example 4
Input: parse_hex_color('#7B1FA2')
Output: 4286259106
Hints
Hint 1
Check whether the input is a string using `isinstance(hex_string, str)` before doing string manipulations.
Hint 2
Trim whitespace using `.strip()` and remove a single prefix `#` if present.
Hint 3
Only allow string lengths of exactly 6 or 8 after trimming.
Hint 4
Use `int(value, 16)` inside a try-except block to catch parsing errors.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The goal is to safely decode hexadecimal color representations into a 32-bit ARGB packed integer, returning a default fallback (0xFF808080) whenever the input is invalid or improperly formatted.
- Validation & Cleaning:
- Verify that the input parameter is an instance of
str. Ifhex_stringisNoneor another type, return0xFF808080. - Strip leading and trailing whitespace from the string.
- If the string begins with
#, strip the leading#.
- Verify that the input parameter is an instance of
- Length & Hex Conversion:
- Ensure the remaining string has a length of exactly 6 or 8 characters. Any other length returns the fallback value.
- Parse the string using
int(value, 16). If aValueErroris raised, return0xFF808080.
- Format Assembly:
- For 6-character inputs (
RRGGBB), apply a bitwise OR with0xFF000000to set the alpha channel to fully opaque (0xFF). - For 8-character inputs (
AARRGGBB), return the parsed integer directly.
- For 6-character inputs (
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$. String length validation guarantees processing bounded-size strings (up to 8 hex characters).
- Space Complexity: $\mathcal{O}(1)$. Memory usage is limited to small temporary string variables.
from typing import Optional
def parse_hex_color(hex_string: Optional[str]) -> int:
fallback = 0xFF808080
if not isinstance(hex_string, str):
return fallback
value = hex_string.strip()
if value.startswith("#"):
value = value[1:]
if len(value) not in (6, 8):
return fallback
try:
parsed = int(value, 16)
except ValueError:
return fallback
if len(value) == 6:
return 0xFF000000 | parsed
return parsed