13
\$\begingroup\$

Given three integers rgb, output hexadecimal representation as a string.

Input:          Output:
72 61 139       #483D8B
75 0 130        #4B0082
0 255 127       #00FF7F

Shortest most unorthodox code wins

\$\endgroup\$

32 Answers 32

0
\$\begingroup\$

JavaScript: 99 chars (110 Thanks @manatwork):

function h(i){x=(i*=1).toString(16);return 16>i?"0"+x:x}function c(r,g,b){return"#"+h(r)+h(g)+h(b)}

Sample:

#!/usr/bin/smjs

function h(i){x=(i*=1).toString(16);return 16>i?"0"+x:x}
function c(r,g,b){return"#"+h(r)+h(g)+h(b)}

if (typeof(arguments[2]) != "undefined" )
    print(c(arguments[0],arguments[1],arguments[2]));

var line;
while (line=readline()) {
    var a=line.split(" ");
    print(c(a[0],a[1],a[2]));
};

In action:

rgb.js 14 15 16 <<< $'15 16 17\n16 17 18'
#0e0f10
#0f1011
#101112

JS Snippet (216)

function h(i){x=(i*=1).toString(16);return 16>i?"0"+x:x}
function c([r,g,b]){return"#"+h(r)+h(g)+h(b)}
function d(){o.innerHTML="";t.value.split("\n").forEach(
function(l){o.innerHTML+=c(l.split(" "))+"<br>"; })};d()
<textarea id="t" onkeyup="d()">72 61 139
75 0 130
0 255 127</textarea><div id="o"></div>

\$\endgroup\$
  • 1
    \$\begingroup\$ You are multiplying i by 1 twice. Better do i*=1 once. And choose a different name for the local variable, so you can leave out the var keyword. I don't have smjs, but function h(i){x=(i*=1).toString(16);return 16>i?"0"+x:x}function c(r,g,b){return"#"+h(r)+h(g)+h(b)} should do the same in 99 characters. \$\endgroup\$ – manatwork Nov 11 '13 at 11:19
  • \$\begingroup\$ @manatwork smjs is the binary tool from spidermonkey, also available as standard Debian packakge. \$\endgroup\$ – F. Hauri Nov 11 '13 at 14:23
  • \$\begingroup\$ Oops. Actually I know+use+enjoy that interpreter, but I always met it with then name js. \$\endgroup\$ – manatwork Nov 11 '13 at 14:53
0
\$\begingroup\$

javascript (ES6), 55

alert('#'+(r<<16|g<<8|b).toString(16).padStart(6,'0'))
\$\endgroup\$
  • \$\begingroup\$ You may want to place a # before your language name and byte count to make it a header. Also, is this ES6? \$\endgroup\$ – bkul Oct 7 '15 at 2:22

protected by Community Oct 6 '15 at 18:47

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.