MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / HEXToRGB

Function HEXToRGB

conversion/rgbhex.go:12–39  ·  view source on GitHub ↗

HEXToRGB splits an RGB input (e.g. a color in hex format; 0x ) into the individual components: red, green and blue

(hex uint)

Source from the content-addressed store, hash-verified

10// HEXToRGB splits an RGB input (e.g. a color in hex format; 0x<color-code>)
11// into the individual components: red, green and blue
12func HEXToRGB(hex uint) (red, green, blue byte) {
13 // A hex code is structured like this:
14 // #3498db (light blue) - converted to binary:
15 // 00110100 10011000 11011011
16 // <red> <green> <blue>
17
18 // To get the blue value we use the bit operation AND with the bit mask 0xFF (in binary: 11111111)
19 // 00110100 10011000 <11011011> &
20 // 00000000 00000000 11111111 =
21 // 00000000 00000000 <11011011> =
22 blue = byte(hex & 0xFF)
23
24 // To get the green value, we first shift the value 8 bits to the right:
25 // 00110100 <10011000> 11011011 >> 8 =
26 // 00000000 00110100 <10011000> &
27 // 00000000 00000000 11111111 =
28 // 00000000 00000000 <10011000> =
29 green = byte((hex >> 8) & 0xFF)
30
31 // Same as green value, only this time shift 16 to the right
32 // Alternatively, you can apply a bitmask first and then shift it.
33 // <00110100> 10011000 11011011 &
34 // 11111111 00000000 00000000 =
35 // <00110100> 00000000 00000000 >> 16
36 // 00000000 00000000 <00110100> =
37 red = byte((hex >> 16) & 0xFF)
38 return
39}
40
41// RGBToHEX does exactly the opposite of HEXToRGB:
42// it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex

Callers 2

TestHEXToRGBFunction · 0.85
BenchmarkHEXToRGBFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestHEXToRGBFunction · 0.68
BenchmarkHEXToRGBFunction · 0.68