Convert int to RGB or hex color
Eithers of these 3 should work:
SELECT color
, HEX_1 = '#'
+ CONVERT(varchar(6),
CAST(ABS(color) as varbinary(1))
+ CAST(ABS(color/256) as varbinary(1))
+ CAST(ABS(color/256/256) as varbinary(1))
, 2)
, HEX_2 = '#'+
+CONVERT(varchar(2), CAST(ABS(color) as varbinary(1)), 2)
+CONVERT(varchar(2), CAST(ABS(color/256) as varbinary(1)), 2)
+CONVERT(varchar(2), CAST(ABS(color/256/256) as varbinary(1)), 2)
, RGB = 'rgb('
+ CAST(ABS(color)%256 as varchar(3)) + ','
+ CAST(ABS(color/256)%256 as varchar(3)) + ','
+ CAST(ABS(color/256/256)%256 as varchar(3)) + ')'
FROM (
values
(-65280)
, (-65535)
, (-460293)
, (-13606962)
, (-3678732)
) as colors(color)
Output:
color | HEX_1 | HEX_2 | RGB
-65280 | #00FF00 | #00FF00 | rgb(0,255,0)
-65535 | #FFFF00 | #FFFF00 | rgb(255,255,0)
-460293 | #050607 | #050607 | rgb(5,6,7)
-13606962 | #32A0CF | #32A0CF | rgb(50,160,207)
-3678732 | #0C2238 | #0C2238 | rgb(12,34,56)
The CONVERT
with style 2 requires SQL Server 2008 or later.
The expression could be used in a computed column definition, or inline table-valued function.