Update 2010-02-01 Thanks to Sameer for pointing out the short way of doing this: return “#%02X%02X%02X” % (r,g,b)
def tohex(r,g,b): hexchars = "0123456789ABCDEF" return "#" + hexchars[r / 16] + hexchars[r % 16] + hexchars[g / 16] + hexchars[g % 16] + hexchars[b / 16] + hexchars[b % 16]
Python is very convenient when you need to program a simple algorithm. I programmed this RGB to Hex converter in less than 1 minute, including using the function for a few RGB values I needed to convert.
Usualy I just grab a pen and a paper and do the calculations myself for getting either the calculator of windows itself to show up and actually calculate stuff properly (looking to screen, writing down, forgetting to press C, starting again…), or writing a program in a language like C# would just take too much time.
I’ve been using Idle for quite some time as a very good replacement for both my calculator and my pen and paper.
Ah, you’re in Python too! I’m really keen on Python. It’s a beautiful, clean language. To be more phisicatic, it was my first programme language I learned. And I’m still programming in Python.
But about tohex, on my firefox GUI I can’t see the complete code. The last few chars are not on the screen. I don’t know if someone else got the same problem. But I do.
…hexchars[b / 16] + hexchars[b % 16] #the last few chars I could not see. At least I think these are it.
Greetings,
Noud
:p Well.. Python is not a very good language for serious software developing in my opinion, but it rocks at this stuff.
The current CSS of the blog makes the menu float above the other content, therefore other content underneath it will not be put on a new line. I’ll create a new theme and CSS once I got spare time.
The line as it should be
return "#" + hexchars[r / 16] + hexchars[r % 16] + hexchars[g / 16] + hexchars[g % 16] + hexchars[b / 16] + hexchars[b % 16]
A simpler solution:
return ‘#%X%X%X’ % (r, g, b)
Thanks!
Eric, you might want to use
return “#%02X%02X%02X” % (r,g,b) to get a 0 to show up as 00
@Sameer I love it! thanks for the elegant solution.