Hexadecimal To RGB

This algorithm converts hexadecimal color code to RGB color model.



									Public Structure RGB
	Private _r As Byte
	Private _g As Byte
	Private _b As Byte

	Public Sub New(r As Byte, g As Byte, b As Byte)
		Me._r = r
		Me._g = g
		Me._b = b
	End Sub

	Public Property R() As Byte
		Get
			Return Me._r
		End Get
		Set(value As Byte)
			Me._r = value
		End Set
	End Property

	Public Property G() As Byte
		Get
			Return Me._g
		End Get
		Set(value As Byte)
			Me._g = value
		End Set
	End Property

	Public Property B() As Byte
		Get
			Return Me._b
		End Get
		Set(value As Byte)
			Me._b = value
		End Set
	End Property

	Public Overloads Function Equals(rgb As RGB) As Boolean
		Return (Me.R = rgb.R) AndAlso (Me.G = rgb.G) AndAlso (Me.B = rgb.B)
	End Function
End Structure

Public Shared Function HexadecimalToRGB(hex As String) As RGB
	If hex.StartsWith("#") Then
		hex = hex.Remove(0, 1)
	End If

	Dim r As Byte = CByte(HexadecimalToDecimal(hex.Substring(0, 2)))
	Dim g As Byte = CByte(HexadecimalToDecimal(hex.Substring(2, 2)))
	Dim b As Byte = CByte(HexadecimalToDecimal(hex.Substring(4, 2)))

	Return New RGB(r, g, b)
End Function

Private Shared Function HexadecimalToDecimal(hex As String) As Integer
	hex = hex.ToUpper()

	Dim hexLength As Integer = hex.Length
	Dim dec As Double = 0

	For i As Integer = 0 To hexLength - 1
		Dim b As Byte = CByte(AscW(hex(i)))

		If b >= 48 AndAlso b <= 57 Then
			b -= 48
		ElseIf b >= 65 AndAlso b <= 70 Then
			b -= 55
		End If

		dec += b * Math.Pow(16, ((hexLength - i) - 1))
	Next

	Return CInt(Math.Truncate(dec))
End Function
								


Example

									Dim data As String = "#520057"
Dim value = HexadecimalToRGB(data)
								


Output

									R: 82
G: 0
B: 87