How to convert Color to Hex and Hex to Color using C# and VB.NET

To convert a Color to Hex and vice versa using C# and VB.NET you can use the snippets below.

Sample C#

private static String ColorToHex(Color inputColor)
{
	return ColorTranslator.ToHtml(inputColor);
}

private static Color HexToColor(string hexInput)
{
	return ColorTranslator.FromHtml(hexInput);
}

Sample VB.NET (autoconverted)

Private Shared Function ColorToHex(inputColor As Color) As [String]
	Return ColorTranslator.ToHtml(inputColor)
End Function

Private Shared Function HexToColor(hexInput As String) As Color
	Return ColorTranslator.FromHtml(hexInput)
End Function

Please rate this snippet

How to convert int to hex and hex to int in C# or VB.NET

How to convert int to hex and hex to int in C# or VB.NET?

Example C#

const int intValue = 3190174; // start int value
var resultHex = intValue.ToString("X"); // convert to Hex, result (uppercase) == 30AD9E
resultHex = intValue.ToString("x"); // convert to Hex, result (lowercase) == 30ad9e
var resultInt = int.Parse(resultHex, System.Globalization.NumberStyles.HexNumber); // convert to back to int, result == 3190174

Example VB.NET

Const  intValue As Integer = 3190174 'start int value
Dim resultHex = intValue.ToString("X") ' convert to Hex, result (uppercase) == 30AD9E
resultHex = intValue.ToString("x") ' convert to Hex, result (lowercase) == 30ad9e
Dim resultInt = Integer.Parse(resultHex, System.Globalization.NumberStyles.HexNumber) ' convert to back to int, result == 3190174

see also Standard Numeric Format Strings in the MSDN.

Please rate this snippet