RGB To Hexadecimal
This algorithm converts RGB color model to hexadecimal color code.
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 RGBToHexadecimal(rgb As RGB) As String
Dim rs As String = DecimalToHexadecimal(rgb.R)
Dim gs As String = DecimalToHexadecimal(rgb.G)
Dim bs As String = DecimalToHexadecimal(rgb.B)
Return "#"c & rs & gs & bs
End Function
Private Shared Function DecimalToHexadecimal(dec As Integer) As String
If dec <= 0 Then
Return "00"
End If
Dim hex As Integer = dec
Dim hexStr As String = String.Empty
While dec > 0
hex = dec Mod 16
If hex < 10 Then
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString())
Else
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString())
End If
dec /= 16
End While
Return hexStr
End Function
Example
Dim data As New RGB(82, 0, 87)
Dim value = RGBToHexadecimal(data)
Output
#520057