How to convert from HEX color to RGB in C#

1 Answer

0 votes
using System;
using System.Globalization;

public class HexToRgbConverter
{
    public static (int R, int G, int B) HexToRgb(string hex) {
        // Remove the '#' character if present
        hex = hex.TrimStart('#');

        // Parse the hex string into an integer
        int hexValue = int.Parse(hex, NumberStyles.HexNumber);

        // Extract the RGB components
        int r = (hexValue >> 16) & 0xFF;
        int g = (hexValue >> 8) & 0xFF;
        int b = hexValue & 0xFF;

        return (r, g, b);
    }

    public static void Main()
    {
        string hexColor = "#FF5705";
        
        var (r, g, b) = HexToRgb(hexColor);
        
        Console.WriteLine($"RGB: ({r}, {g}, {b})");
    }
}


 
/*
run:

RGB: (255, 87, 5)
     
*/

 



answered Mar 6, 2025 by avibootz

Related questions

1 answer 55 views
1 answer 119 views
2 answers 113 views
2 answers 85 views
2 answers 98 views
2 answers 99 views
2 answers 109 views
...