© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
4 replies
Angius

✅ Hex color converter breaks on 3-digit and 4-digit values

I made this nifty lil' converter from hexadecimal strings to
System.Drawing.Color
System.Drawing.Color
s. It works perfectly for 6-digit and 8-digit values, but tests fail for 3-digit and 4-digit ones.
public static Color ParseHexColor(this string input)
{
    var hex = input.Trim('#');
    if (!int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var num))
    {
        throw new ArgumentException("Not a valid hexadecimal number", nameof(input));
    }
    
    return hex.Length switch
    {
        3 => Color.FromArgb(((num >> 8) & 0xF) * 0xFF / 0xF, ((num >> 4) & 0xF) * 0xFF / 0xF, (num & 0xF) * 0xFF / 0xF),
        4 => Color.FromArgb(((num >> 12) & 0xF) * 0xFF / 0xF,((num >> 8) & 0xF) * 0xFF / 0xF, ((num >> 4) & 0xF) * 0xFF / 0xF, (num & 0xF) * 0xFF / 0xF),
        6 => Color.FromArgb((num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF),
        8 => Color.FromArgb((num >> 24) & 0xFF, (num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF),
        _ => throw new ArgumentException("Unknown format", nameof(input))
    };
}
public static Color ParseHexColor(this string input)
{
    var hex = input.Trim('#');
    if (!int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var num))
    {
        throw new ArgumentException("Not a valid hexadecimal number", nameof(input));
    }
    
    return hex.Length switch
    {
        3 => Color.FromArgb(((num >> 8) & 0xF) * 0xFF / 0xF, ((num >> 4) & 0xF) * 0xFF / 0xF, (num & 0xF) * 0xFF / 0xF),
        4 => Color.FromArgb(((num >> 12) & 0xF) * 0xFF / 0xF,((num >> 8) & 0xF) * 0xFF / 0xF, ((num >> 4) & 0xF) * 0xFF / 0xF, (num & 0xF) * 0xFF / 0xF),
        6 => Color.FromArgb((num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF),
        8 => Color.FromArgb((num >> 24) & 0xFF, (num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF),
        _ => throw new ArgumentException("Unknown format", nameof(input))
    };
}
image.png
image.png
image.png
image.png
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

✅ How can I convert/flatten an 8-Digit Hex color (Alpha) to a 6-Digit Hex color (Assuming white BG)
C#CC# / help
2y ago
Change Hex value (Color) as approaching target
C#CC# / help
2mo ago
im trying to code a 4 digit password cracker
C#CC# / help
4y ago
checked number digit
C#CC# / help
4y ago