10
\$\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\$
3

32 Answers 32

1
2
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\$
3
  • 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
    Commented Nov 11, 2013 at 11:19
  • \$\begingroup\$ @manatwork smjs is the binary tool from spidermonkey, also available as standard Debian packakge. \$\endgroup\$ Commented Nov 11, 2013 at 14:23
  • \$\begingroup\$ Oops. Actually I know+use+enjoy that interpreter, but I always met it with then name js. \$\endgroup\$
    – manatwork
    Commented Nov 11, 2013 at 14:53
0
\$\begingroup\$

javascript (ES6), 55

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

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