Full Version: Converting RGB to Hexadecimal [Program]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is a 'continuation' of my thread on Converting RGB to Hexadecimals.

Now we will be learning how to make a program to convert the two.

There are no imports in this project, only definitions.

First, we will be defining hexrgb. This just lets us convert from hexadecimal to RGB values. It's simple.

def hexrgb(v):
    if v[0] == '#':
        v = v[1:]
    assert(len(v) == 6)
    rgb = (int(v[:2],16), int(v[2:4],16), int(v[4:6],16))

First, if the value provided starts with a hashtag, we remove that so it doesn't mess with the rest of the code. Then it makes sure the length of the value given is 6 digits long. After that, it divides certain parts of the value provided and finishes with our RGB value.

def rgbhex(rgb):
    print('#%02x%02x%02x' % rgb)

Next definition, rgbhex, uses the percent operator to change RGB values to hexadecimal. That is literally all that we need to use this program.

So how does this work? An example of this work would be doing it in the code itself. Here;
hexrgb('#FF00FF') # = 255,0,255 (Pink)
rgbhex((255,0,0)) # = FF0000 (Red)

If you haven't read the original thread that lead up to this program, click [here].
If you would like to see the project on GitHub, click [here]