Function RgbToHex(color As Long) As String
Dim r As Long, g As Long, b As Long
r = color And &HFF
g = (color / 256&H100) And &HFF
b = (color / 65536&H10000) And &HFF
RgbToHex = Right$(Hex$(16777216&H1000000 + 65536&H10000 * r + 256&H100 * g + b), 6)
End Function
Assuming the VB6 compiler really doesn't inline constant expressions, this is probably one of the fastest ways to implement RgbToHex.
Instead of using a mixture of ColorConstants and magic numbers, I have restricted my code to magic numbers only. And these numbers are not really magic, since they are all powers of 2 or very close to them. If the compiler can inline constants, 65536 can be written as (256 * 256)
.
Instead of converting every color channel separately to a hex number, it is more efficient to first combine the color channels and then convert them once.
I renamed l
to color
since a lowercase ell is hard to distinguish from the digit 1 or a capital i.
The number &H1000000
makes sure that the output is always 6 digits long, by producing a 7-digit hex number first and then only keeping the last 6 hex digits of that number. If this number were not there, black would be output as 0
instead of 000000
.