Colore RGB int in esadecimale


13

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


16
La nostra FAQ dice che Tutte le domande su questo sito ... dovrebbero avere un criterio vincente primario oggettivo, in modo che sia possibile decidere indiscutibilmente quale voce dovrebbe vincere. . Il più breve è oggettivo, ma "il più poco ortodosso" non lo è. Inoltre, il tag code-golf dovrebbe essere usato solo se la condizione vincente è solo il codice più corto; e il tag code-challenge dovrebbe essere usato solo se il tag code-golf non lo è.
Peter Taylor,

e accettare il vincitore prima di un po 'di tempo (in questo caso, non era nemmeno 24 ore) tipo di scoraggia ulteriori contributi ...
woliveirajr

@PeterTaylor Spiacente, mi assicurerò di leggere le linee guida d'ora in poi :( Immagino che tu abbia ragione non ortodossa è molto vaga
Quillion

Risposte:


14

Rubino: 19 personaggi

$_=?#+"%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

16

Rubino

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:

image

Esecuzione di esempio:

c:\a\ruby>rgb2hex
255 100 0
#FF6400

Questo è geniale!
Albert Renshaw,

6

q / k (3 caratteri)

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$

1
Questo manca il cancelletto (#) richiesto per gli output di esempio nella domanda.
Iszi,

5

PowerShell: 71 52 51 41

Grazie a @manatwork per la segnalazione ForEach-Objectpuò essere utilizzato al posto di un forloop.
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)
    }
)

Crea il loop foreach($i in 1,2,3)per ridurlo a 68 caratteri.
arte

@manatwork Non penso che sia la sintassi corretta per un 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!
Iszi,

Non ho idea se sia la sintassi corretta o meno, ma il riferimento SS64 foreachlo menziona e funziona per me. (Non
ho

@manatwork È interessante. Mi piacerebbe scavare in giro e capire cosa c'è di sbagliato in questo un po 'di più (stavo ottenendo errori "token inaspettati" negli errori "...") un'altra volta. È possibile che l'articolo SS64 sia stato scritto per una versione diversa di PowerShell - non ne sono sicuro. Per ora, ho confermato che (1..3)|%funziona e porta la sceneggiatura a 56 caratteri. Lo modificherò nella risposta e sicuramente ti darò credito per l'idea. Grazie ancora!
Iszi,

2
Oh, dang. È possibile ottenere questo a 41 utilizzando -join: '#'+-join(1..3|%{"{0:X2}"-f+(read-host)}).
Joey,

4

bash 22 21 caratteri

(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

Aggiunto il 06-10-2015: bash ( metodo più non ortodosso ) 84 83 caratteri

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

Un altro approccio

#!/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'>&nbsp;</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:

RGB int 2 hex viewer converter

Dove è possibile ruotare la rotellina del mouse per modificare i valori (con il tasto MAIUSC premuto per passo di 15) ...


In realtà la nuova riga finale non è stata richiesta e solo "#" deve uscire, quindi printf \#%02X%02X%02Xè sufficiente.
arte

Aggiunto un metodo più poco ortodosso :
F. Hauri,

Lol. Quel circuito interno è davvero incredibilmente poco ortodosso.
arte

@manatwork grazie, trovo d+=${c[$b$a 0x10]}qualcosa di sexy !
F. Hauri,

1
... o forse d+=${c[$b$a 020]}farà il lavoro e avrà un bell'aspetto
F. Hauri,

3

Perl, 31 caratteri

perl -nE 'say"#",map{unpack H2,chr}split'

È difficile rendere poco ortodosso un programma così breve, ma penso che funzioni.


Mi piace questa risposta :) ancora un po 'e penso che potrei accontentarmi di questo se non ci fosse niente di meglio.
Quillion

Freddo! Solo una unpackdomanda: puoi rendere l'esadecimale a ... maiuscolo, come nella domanda?
arte

@manatwork Ho provato a trovare un modo per farlo dentro 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.
breadbox

Grazie, @breadbox. Quei piccoli difficili packe unpacknon entrano mai nel mio stile di programmazione. Quindi non è abbastanza ortodosso per me.
arte

Conteggio errato. Questo rende 30 caratteri!
F. Hauri,

3

Action Script 3 | 43 caratteri

trace("#"+(72<<16|61<<139|b).toString(16));

Produzione: #483D8B


Non puoi lasciare molto spazio bianco qui? Non conosco Action Script, ma non sembrano necessari
Cruncher,

@ Cruncher sì, scusa, una delle mie prime risposte qui.
Ilya Gazman,

2
Uccidi il punto e virgola alla fine per salvare un carattere
Maniglia della porta

3

Perl 24 caratteri

perl -ne 'printf"#"."%02x"x3,split'
13 31 133
#0d1f85

Spiacente, non è così sexy che usare unpack, ma più corto!

More obscure version:

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

3

><> 103 60

"#"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"


Will provide explanation on request. If you can figure it out I'd rather not bother
Cruncher

2

Forth, 62 characters

: D 0 <<# # # #> TYPE #>> ; 35 EMIT HEX SWAP ROT D D D DECIMAL

doesn't work for 1 1 1 which should output #010101
ratchet freak

Hi @ratchetfreak. It works for me. Just tested with gforth. Giving it 1 1 1 outputs #010101. Any other values 0-255 also work. What environment or forth are you using?
Darren Stone

2

C (67 chars no main boilerplate)

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


Wait, readf? Shouldn't that be scanf?
breadbox

@breadbox ah yeah I spent too much time in D; either way no difference in char count
ratchet freak

2

Dc: 35 32 characters

[#]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

Dc: 27 24 characters

(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

2
There are not enough dc answers on this website.
breadbox

2

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.


Nice one, but fails on the 3rd sample posted in the question.
manatwork

Ah, good call. Fixed.
Casey Chu

2
Using eval('(('+DEC.replace(/ /g,'<<8)+')) instead of eval('256*(256*('+DEC.replace(/ /g,')+')) let you save 5 chars!
F. Hauri

2

PowerShell, 45

'#'+-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.


Nice work! Shows I still have much to learn about golfing!
Iszi

Oh, your idea with the variables was clever too; would have never crossed my mind. It just so happens that it's longer than my usual favourite: -split and -join.
Joey

2

powershell 37

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

You can save a couple bytes by getting rid of the [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"
AdmBorkBork

@TimmyD dont know if removing [byte] works correctly in all version in a version in which i tested (iirc 2.0 in xp ) without [byte] it was not concatenating as hex but as ints ie 72 61 139 was #7261139 not #483d8b "#$o" inside quotes isnt a string literal but evaluated string nice to know thanks comments about hex conversion will be appreciated
blabb

It's apparently a difference between PowerShell v2 and v3 -- must be something in how the corresponding .NET version handles hexadecimal conversion, but I can't find documentation on it.
AdmBorkBork

2

R, 16 bytes

That's it. Use the built in.

rgb(r,g,b,m=255)

1

C, 67 73 Characters (65 Chars excluding main)

main(){int a,b,c;scanf("%d%d%d",&a,&b,&c);printf("#%02X%02X%02X",a,b,c);}

Boring C program - very orthodox.


doesn't work with a b or c smaller than 16
ratchet freak

Changed %X to %02X.
Ian James

1

Python 2.7 (80 Characters)

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?


Maybe use format strings? '%02x' seems to be what everyone else has done.
jqblz

1

Befunge-98, 45 characters

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".)


1

Game Maker Language, 175 (Error at position 81)

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.

Source


1

Gema, 93 characters

\B=@set{x;0123456789abcdef}\#
<D>=@substring{@div{$1;16};1;$x}@substring{@mod{$1;16};1;$x}
?=

Sample run:

bash-4.3$ gema '\B=@set{x;0123456789abcdef}\#;<D>=@substring{@div{$1;16};1;$x}@substring{@mod{$1;16};1;$x};?=' <<< '0 255 127'
#00ff7f

1

Burlsque, 12 bytes (10 bytes for lower-case)

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 #

Try online here.

Bonus:

To convert it back use this:

blsq ) "#483d8b"[-2cob6
{72 61 139}

1

Powershell, 28 bytes

'#{0:X2}{1:X2}{2:X2}'-f$args

Test script:

$f = {

"#{0:X2}{1:X2}{2:X2}"-f$args
}

@(
    ,('#483D8B',72, 61, 139)
    ,('#4B0082',75,  0, 130)
    ,('#00FF7F',0 ,255, 127)
) | % {
    $e,$a = $_
    $r = &$f @a
    "$($r-eq$e): $r"
}

Output:

True: #483D8B
True: #4B0082
True: #00FF7F

0

Python3.3 @ 60 chars

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

0

Clojure 76 Characters

This might be late, for the sake of completeness:

(defn hexy [r g b] (reduce str (cons "#" (map #(format "%02X" %) [r g b]))))

Example calls:

(hexy 0 255 127)
"#00FF7F"

0

Mathematica, 40 characters

f = StringJoin["#", IntegerString[#, 16, 2]] &

rgbs = {{72, 61, 139}, {75, 0, 130}, {0, 255, 127}}

f /@ rgbs // Column

#483d8b

#4b0082

#00ff7f


0

Common Lisp, 39 characters

(format()"#~@{~2,'0x~}"#1=(read)#1##1#)

Read three integers, return a string.


0

Javascript ES6, 63 bytes

h=>'#'+h.split` `.map(x=>(x<16?0:'')+(x*1).toString(16)).join``

Coincidentally, I ended up writing almost exactly the same thing as you before I saw yours. Very nice =) They're close enough that I won't post mine, but you can save a few bytes on your mapping with this: x=>(x<16?0:'')+x.toString(16)
Mwr247

1
Also, no need to include the 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.
Mwr247

Whoops. Meant the map to be: x=>(x<16?0:'')+(x*1).toString(16) Yours and my first one there currently give wrong values for x>9.
Mwr247

This currently returns #7261139 instead of #483D8B for the first test case.
Dennis

0

Python 2, 40 bytes

s='#';exec's+="%02X"%input();'*3;print s

Reads the input from three separate lines. Abuses exec and string multiplication.

Example usage:

$ python2 rgbint.py
72
61
139
#483D8B

$ python2 rgbint.py
75
0
130
#4B0082

$ python2 rgbint.py
0
255
127
#00FF7F

0

Python (55 chars)

'#'+''.join([hex(int(i))[2:].upper() for i in input()])
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.