Skip to content

Instantly share code, notes, and snippets.

@mykhailokrainik
Created October 19, 2022 18:27
Show Gist options
  • Save mykhailokrainik/85e5ecfd69491ebc49c16387630fbb70 to your computer and use it in GitHub Desktop.
Save mykhailokrainik/85e5ecfd69491ebc49c16387630fbb70 to your computer and use it in GitHub Desktop.
RGB To Hex Conversion
def rgb(r, g, b)
a1, b1 = split_num(r); p a1,b1
a2, b2 = split_num(g); p a2,b2
a3, b3 = split_num(b); p a3,b3
"#{dec_to_hex(a1)}#{dec_to_hex(b1)}#{dec_to_hex(a2)}#{dec_to_hex(b2)}#{dec_to_hex(a3)}#{dec_to_hex(b3)}"
end
def split_num(num)
if num > 255 then num = 255 end
if num < 0 then num = 0 end
a = num / 16.0
b = a.modulo(1).round(2)
c = a.floor
d = (b * 16).round
[c, d]
end
def dec_to_hex(num)
case num
when 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
num
when 10
'A'
when 11
'B'
when 12
'C'
when 13
'D'
when 14
'E'
when 15
'F'
else
'0'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment