KatInterview

Parse Hex Color Code to ARGB Integer

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringsparsingmath-bits

Last 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

  1. 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.
  2. 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) to 0xFF by performing a bitwise OR with 0xFF000000 (i.e. 0xFF000000 | parsed).
    • If the stripped string length is exactly 8 characters (AARRGGBB), return the parsed base-16 integer directly.
  3. Fallback Output (0xFF808080): Return 0xFF808080 (4286578816 in decimal) if any of the following occur:

    • The input hex_string is not a string (e.g. None or 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).

Constraints

  • The input hex_string can be of any type, including None.
  • 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.