Convert HEX to closest X11 Color Number

Viewed 10521

I'm looking for a Algorithm/Way to convert given HEX (e.g. #111111 R:0x11, G:0x11, B:0x11) to the closest X11 color number (Terminal is either 88 or 256 colors) using either Python, PHP, or VIM script and I was wondering if someone here knows a way or point me to a direction to do this.

Thanks in Advance.

5 Answers

Here is python implementation that is constant time:

N = []
for i, n in enumerate([47, 68, 40, 40, 40, 21]):
    N.extend([i]*n)

def rgb_to_xterm(r, g, b):
    mx = max(r, g, b)    
    mn = min(r, g, b)

    if (mx-mn)*(mx+mn) <= 6250:
        c = 24 - (252 - ((r+g+b) // 3)) // 10
        if 0 <= c <= 23:
            return 232 + c

    return 16 + 36*N[r] + 6*N[g] + N[b]
Related