Dati tre numeri interi rgb, genera una rappresentazione esadecimale come stringa.
Input: Output:
72 61 139 #483D8B
75 0 130 #4B0082
0 255 127 #00FF7F
Vince il codice più breve più poco ortodosso
Dati tre numeri interi rgb, genera una rappresentazione esadecimale come stringa.
Input: Output:
72 61 139 #483D8B
75 0 130 #4B0082
0 255 127 #00FF7F
Vince il codice più breve più poco ortodosso
Risposte:
$_=?#+"%02X"*3%$F
Esecuzione di esempio:
bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '72 61 139'
#483D8B
bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '75 0 130'
#4B0082
bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '0 255 127'
#00FF7F
Stavo andando di più per la parte "non ortodossa". ;)
10;a= gets. split
. map {| x| #x
"%02X" %( x. to_i)
}; $> << ?# << a[
00 .. 1+2]. join;
Il carattere (sul mio browser web) è un po 'alto, quindi sembra distorto, ma sembra migliore in Courier New:

Esecuzione di esempio:
c:\a\ruby>rgb2hex
255 100 0
#FF6400
Non esattamente non ortodosso ma piuttosto corto
4h$
Esempio
q)4h$ 72 61 139
0x483d8b
Per abbinare esattamente il formato di output nella domanda, possiamo fare (per 9 caratteri):
"#",/$4h$
Grazie a @manatwork per la segnalazione
ForEach-Objectpuò essere utilizzato al posto di unforloop.
Grazie a @Joey per aver sottolineato che avrei potuto usare-joinl'output del loop, invece di doverlo inserire in variabili.
Codice golfizzato:
'#'+-join(1..3|%{"{0:X2}"-f+(read-host)})
Nota:
Non ci sono errori nel controllo qui per input non validi. Lo script prenderà felicemente 256, 4096 e 65536 come input, quindi output # 100100010000 (che ovviamente non funzionerà come RGB).
Ungolfed, con commenti:
# Put a hashtag in front of the output.
'#'+
# Join the nested code into one string.
-join(
# Pipe 1..3 to ForEach-Object to run a loop three times.
1..3|%{
# Take user input and format it as hex, with minimum two digits in output.
"{0:X2}"-f+(read-host)
}
)
foreach($i in 1,2,3)per ridurlo a 68 caratteri.
foreachin PowerShell. (Almeno, non sono stato in grado di far funzionare alcune esecuzioni di test.) Tuttavia, usando la sintassi corretta, un alias incorporato e un altro collegamento PowerShell che ho scoperto di recente, penso di avere qualcosa di meglio, la rasatura altri 12 caratteri dal tuo suggerimento. (1..3)|%{...}(Inserisci una parentesi tra parentesi dello script esistente al posto dei puntini di sospensione.) Devo ancora testarlo completamente nello script, ma grazie per avermi indicato in quella direzione!
(1..3)|%funziona e porta la sceneggiatura a 56 caratteri. Lo modificherò nella risposta e sicuramente ti darò credito per l'idea. Grazie ancora!
-join: '#'+-join(1..3|%{"{0:X2}"-f+(read-host)}).
(Grazie @manatwork per 1 carattere usando \anziché le doppie virgolette)
printf \#%02X%02X%02X 12 12 12
#0C0C0C
o leggendo STDIN in un ciclo: 48 caratteri:
while read f;do printf "#%02X%02X%02X\n" $f;done <<<$'72 61 139\n75 0 130\n0 255 127'
#483D8B
#4B0082
#00FF7F
c=({0..9} {a..f}) d=\#;for b;do for a in / %;do d+=${c[$b$a 020]};done;done;echo $d
Lo so, potrebbe essere 82 caratteri se 020scritto 16, ma preferisco questo ... O forse d+=${c[$b$a 0x10]}quale era il primo post.
hexcolor() {
local a b c=({0..9} {a..f}) d=\#
for b ;do
for a in / % ;do
d+=${c[$b$a 0x10]}
done
done
echo $d
}
hexcolor 72 61 139
#483d8b
hexcolor 75 0 130
#4b0082
hexcolor 0 255 127
#00ff7f
#!/bin/bash
browser=firefox # google-chrome iceweasel
url="data:text/html;charset=UTF-8,<html><head></head><body>"
url+="<script type='text/javascript'>
function h(i){var h=i.toString(16);if(16>1*i)h='0'+h;
return h};function C(r,g,b){return'\043'+h(r)+h(g)+h(b)};
function m(){ var r=1.0*R.value; var g=1.0*G.value; var b=1.0*B.value;
var fore='black';if(384>r+g+b)fore='white';var c=C(r,g,b);
s.setAttribute('style','background:'+c+';color:'+fore+';');s.innerHTML=c};
function w(e){console.log(e);var val=e.target.value;var q=1;if(e.shiftKey)
q=15;if(e.detail){if(e.detail>0){q=0-q;}}else if(0>e.wheelDelta){q=0-q;};
val=1*val+q;if(val>255)val=255;if(0>val)val=0;e.target.value=val;m(); };
function k(e){console.log(e);var val=e.target.value;var q=1;if(e.shiftKey)q=
15;if(e.keyCode==38){val=1*val+q;if(val>255)val=255;e.target.value=val;m();}
else if(e.keyCode==40){val=1*val-q;if(0>val)val=0;e.target.value=val;m();}};
function n(){R=document.getElementById('R');G=document.getElementById('G');
B=document.getElementById('B');s=document.getElementById('s');
R.addEventListener('DOMMouseScroll',w);R.addEventListener('mousewheel',w);
G.addEventListener('DOMMouseScroll',w);G.addEventListener('mousewheel',w);
B.addEventListener('DOMMouseScroll',w);B.addEventListener('mousewheel',w);
m();};var R, G, B, s;window.onload=n;
</script><style>div{display:inline-block;width:10em;}</style>
<div id='s'> </div>"
input="%s:<input type='text' size='5' value='200'"
input+=" onKeyDown='k(event)' onChange='m()' id='%s' />"
for c in R G B ;do
printf -v add "$input" $c $c
url+="$add"
done
$browser "$url"
Verrà visualizzata una finestra del browser con:

Dove è possibile ruotare la rotellina del mouse per modificare i valori (con il tasto MAIUSC premuto per passo di 15) ...
printf \#%02X%02X%02Xè sufficiente.
d+=${c[$b$a 0x10]}qualcosa di sexy !
d+=${c[$b$a 020]}farà il lavoro e avrà un bell'aspetto
perl -nE 'say"#",map{unpack H2,chr}split'
È difficile rendere poco ortodosso un programma così breve, ma penso che funzioni.
unpackdomanda: puoi rendere l'esadecimale a ... maiuscolo, come nella domanda?
unpack, ma senza fortuna. Un modo è usare sprintfinvece di unpack, ma è più lungo e completamente ortodosso. L'altro modo è semplicemente modificare la stringa in maiuscolo:, map{uc unpack H2,chr}al costo di tre caratteri.
packe unpacknon entrano mai nel mio stile di programmazione. Quindi non è abbastanza ortodosso per me.
trace("#"+(72<<16|61<<139|b).toString(16));
Produzione: #483D8B
perl -ne 'printf"#"."%02x"x3,split'
13 31 133
#0d1f85
Spiacente, non è così sexy che usare unpack, ma più corto!
But if you really prefer to use unpack, then you could:
$==24;s/\d+[\n ]*/{$=-=8;($&<<$=).do{rand>.5?qw<+>[0]:"|"}}/eg;$_=
pack("N",eval($_.587.202.560));say$1,unpack("H6",$2)if/^(.)(.*)$/s
For sample, it's not the shorter version, but I like it! ( Note the use of rand for randering this :-)
perl -nE '
$==24;s/\d+[\n ]*/{$=-=8;($&<<$=).
do{rand>.5?qw<+>:"|"}}/eg;$_=pack(
"N",eval($_.587.202.560) );say $1,
unpack("H"."6",$2) if /^(.)(.*)$/s
' <<< $'72 61 139\n75 0 130\n0 255 127'
#483d8b
#4b0082
#00ff7f
"#"or>1[:82*%:}-82*,86*+:"9"v
;^?l ]o+*7)"9":+*68o+*7)<
Made use of the wasted white space, and moved some code into it
Run with command line inputs:
python fish.py generateHex.fish -v 255 36 72
output: "#FF2448"
: D 0 <<# # # #> TYPE #>> ; 35 EMIT HEX SWAP ROT D D D DECIMAL
1 1 1 outputs #010101. Any other values 0-255 also work. What environment or forth are you using?
int r,g,b;
scanf("%d %d %d",&r,&b,&g);
printf("#%06x",r<<16|g<<8|b);
the bog standard printf & bit twiddler usage
readf? Shouldn't that be scanf?
[#]n16o?ShShSh[Lhd16/n16%n]ddxxx
Sample run:
bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '72 61 139'
#483D8B
bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '75 0 130'
#4B0082
bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '0 255 127'
#00FF7F
(But needs the input numbers on separate lines.)
[#]n16o[?d16/n16%n]ddxxx
Sample run:
bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'72\n61\n139'
#483D8B
bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'75\n0\n130'
#4B0082
bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'0\n255\n127'
#00FF7F
dc answers on this website.
JavaScript, 89 chars
console.log('#' + ('00000' + eval('256*(256*(' + DEC.replace(/ /g, ')+')).toString(16)).slice(-6))
Converts 72 61 139 to 256*(256*(72)+61)+139 and evals it.
eval('(('+DEC.replace(/ /g,'<<8)+')) instead of eval('256*(256*('+DEC.replace(/ /g,')+')) let you save 5 chars!
'#'+-join(-split(read-host)|%{'{0:X2}'-f+$_})
Or, if it can be used by piping in the data, you can just use
'#'+-join(-split"$input"|%{'{0:X2}'-f+$_})
which brings it down to 42.
-split and -join.
saved one byte thanks to TimmyD
cat rgb2hex.ps1
$args|%{$o+="{0:X2}"-f[byte]$_};"#$o"
wc -c rgb2hex.ps1
38 rgb2hex.ps1
powershell -f .\rgb2hex.ps1 72 61 139
#483D8B
powershell -f .\rgb2hex.ps1 0 255 127
#00FF7F
[byte] since we're given the input as integers, and edit your output to be "#$o" -- that gives 31 bytes for $args|%{$o+="{0:X2}"-f$_};"#$o"
main(){int a,b,c;scanf("%d%d%d",&a,&b,&c);printf("#%02X%02X%02X",a,b,c);}
Boring C program - very orthodox.
x=lambda y: ("0"+hex(int(y))[2:])[-2:]
print "#"+''.join(map(x,input().split()))
I'm looking for a better way to handle the single digit hex values. Any ideas?
Bleh, duplicated code. Oh well. Just a straightforward implementation of radix conversion.
"#",v
7*+,>#@&:97+/"0"+:"9"`7*+,97+%"0"+:"9"`
Sample run
% cfunge tohex.98 <<<'72 61 139'
#483D8B
% cfunge tohex.98
#75 0 130
4800820 255 127
00FF7F
(Note: prints '#' before reading input---the task doesn't forbid this; given three numbers on stdin it produces the right output on stdout. It also doesn't bother with newlines, and as you can see it doesn't add '#' properly when run "interactively".)
Prompts for 3 to 9-digit RGB. Returns hexadecimal with GML hexadecimal sign, $
d=get_string('','')if(d=='')e=""else e="00"h="0123456789ABCDEF"while(d!=''){b=d&255i=string_char_at(h,byte div 16+1)l=string_char_at(h,byte mod 16+1)e+=i+l;d=d>>8}return '$'+e
Make this a script. Also, compile with uninitialized variables treated as 0.
If lower-case is allowed as well then 10 bytes:
psb6\['#+]
Usage:
blsq ) "72 61 139"psb6\['#+]
"#483d8b"
If you desperately need upper-case, add ZZ:
blsq ) "72 61 139"psb6\['#+]ZZ
"#483D8B"
If you don't receive the integers as in a string then go with:
blsq ) {72 61 139}b6\['#+]
"#483d8b"
Explanation:
ps -- parse string
b6 -- to hex
\[ -- concat
'#+] -- prepend #
Bonus:
To convert it back use this:
blsq ) "#483d8b"[-2cob6
{72 61 139}
print("#"+3*"%.2X"%tuple(int(n) for n in input().split()))
Couldn't resist:
[dan@danbook:code_golf/int_to_hex]$ python3.3 int_to_hex.py
176 11 30
#B00B1E
f = StringJoin["#", IntegerString[#, 16, 2]] &
rgbs = {{72, 61, 139}, {75, 0, 130}, {0, 255, 127}}
f /@ rgbs // Column
#483d8b
#4b0082
#00ff7f
h=>'#'+h.split` `.map(x=>(x<16?0:'')+(x*1).toString(16)).join``
x=>(x<16?0:'')+x.toString(16)
r= at the beginning. It still counts as a function even as an anonymous function, since you can invoke it without having to assign anything.
x=>(x<16?0:'')+(x*1).toString(16) Yours and my first one there currently give wrong values for x>9.
#7261139 instead of #483D8B for the first test case.
'#'+''.join([hex(int(i))[2:].upper() for i in input()])