# Challenge

Here's a simple one.

Write a function or program when given a number in base 10 as input, it will return or print that number's value in Hexadecimal.

# Examples

15 -> F
1000 -> 3E8
256 -> 100


# Rules

• No built-in Hexadecimal functions whatsoever
• Letters may be lowercase or uppercase
• You will only need to worry about non-negative integers, no negatives or pesky decimals
• It should work with any arbitrarily large number up to language's default type's limit.
• Newline not mandatory
• As usual, this is , so shortest code measured in bytes wins!
• First problem, hope you guys enjoy! – Random Guy Dec 31 '15 at 2:06
• Are leading zeros allowed in the output, e.g for 32bit numbers 000003E8? – nimi Dec 31 '15 at 3:03
• Any limit on the input? – Loovjo Dec 31 '15 at 3:27
• @nimi Yes, that is allowed. – Random Guy Dec 31 '15 at 6:08
• Fun fact: C++ has a hex builtin. – Matthew Roh Mar 14 '17 at 17:10

# APL (Dyalog APL), 17 bytes

Must be run with ⎕IO←0, which is default on many APL systems.

(⎕D,⎕A)[16⊥⍣¯1⊢⎕]


Try it online!

(⎕D,⎕A)[]Digits concatenated to Alphabet, then indexed by…

16⊥⍣¯1  the inverse of 16-Base-to-Number, i.e. Number-to-Base-16

⊢ applied to

⎕ numeric input

• Isn't this 17 chars and around 23 bytes? – Julie Pelletier Jun 18 '16 at 23:00
• @JuliePelletier No, Dyalog APL uses its own 256 character codepage. – Adám Jun 18 '16 at 23:00
• Oh! Good to know. – Julie Pelletier Jun 18 '16 at 23:02

# Turing Machine Code, 412 bytes

As usual, I'm using the rule table syntax defined here. You can test it on that site or, alternatively, using this java implementation.

0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 A r 4
3 A B r 4
3 B C r 4
3 C D r 4
3 D E r 4
3 E F r 4
3 F 0 l 3
4 * * r 4
4 _ _ r A


Counts down from the input in base 10 while counting up from 0 in base 16. On decrementing zero, it erases the input block and terminates.

• This is really cool, it takes 10*n + 33 instructions to complete for any arbitrary n. I don't understand the code though. – Magic Octopus Urn Oct 31 '18 at 16:58
• @MagicOctopusUrn It creates a new block of cells to the left of the input, initially containing a 0. Then, it repeatedly decrements the input block in base 10 while incrementing the output block in base 16, until it attempts to decrement an empty cell during the decrement cycle [which tells it that the input block is now 0], at which point it cleans up the tape (so only the output remains on the tape) before halting. – SuperJedi224 Oct 31 '18 at 21:44
• @MagicOctopusUrn Also your equation for the runtime is incorrect (I don't know what the correct general equation is though, just that that clearly isn't it). Try it with an input of 2, for example. – SuperJedi224 Oct 31 '18 at 22:01
• probably not. Seemed close for high values though. I know nothing about it and was attempting to see patterns. – Magic Octopus Urn Nov 1 '18 at 13:35

# Java, 92 89 bytes

String x(int v){String z="";for(;v>0;v/=16)z="0123456789ABCDEF".charAt(v%16)+z;return z;}


# Javascript, 49 43 bytes.

h=i=>(i?h(i>>4):0)+"0123456789abcdef"[i%16]


6 bytes saved by user81655.

Test it here.

This has two leading zeroes, which is allowed by the rules.

Here's a version without leading zeroes: (47 bytes).

h=i=>(i>15?h(i>>4):"")+"0123456789abcdef"[i%16]


Test it here.

Both of these uses exactly the same approach as my Python answer.

• Use binary AND. i&15 will automatically convert to integer, dropping decimals. No need of ~~ – edc65 Dec 31 '15 at 13:43
• I saved 3 bytes and one leading zero: h=i=>i&&h(i>>4)+"0123456789abcdef"[i&15] – Neil Jan 1 '16 at 21:01

# CJam, 22 21 bytes

ri{Gmd_A<70s=+\}h;]W%


Thanks to @MartinBüttner for golfing off 1 byte!

Try it online!

### How it works

ri                      e# Read an integer from STDIN.
{             }h      e# Do:
Gmd                  e#   Push qotient and residue of the division by 16.
_A<               e#   Check if the residue is less than 10.
70s            e#   Push "70".
=           e#   Select the character that corresponds to the Boolean.
+          e#   Add the character to the digit.
e#   This way, 10 -> 'A', etc.
\        e#   Swap the quotient on top of the stack.
e# While the quotient is non-zero, repeat the loop.
;     e# Pop the last quotient.
]W%  e# Reverse the stack.

• Same byte count: ri{Gmd_9>7*sc+\}h;]W% – Martin Ender Dec 31 '15 at 16:28

# Pyth, 332621 20 bytes

This was a fun one.

sm@+jkUTGi_d2_c_.BQ4


Try it online.

Explained:

                .BQ      Convert input to a binary string, e.g. 26 -> '11010'
_c_   4     Reverse, chop into chunks of 4, and reverse again. We reverse
because chop gives a shorter last element, and we want a shorter
first element: ['1', '0101']
Reversing three times is still shorter than using .[d4 to pad the
binary string to a multiple of 4 with spaces.
m                       Map across this list:
i_d2                Take the value of the reversed string in binary,
@                          and use it as an index into the string:
+jkUTG                    '0123456789abcdefghijklmnopqrstuvwxyz'
(The alphabet appended to the range 0 to 10)
s                        Concatenate to create the final string.

• Can you add an explanation? – TanMath Dec 31 '15 at 2:53
• Sure, which one are you interested in? – Luke Dec 31 '15 at 3:02
• The most intersting answer! ;) it doesn't matter...Although it is a good idea to post explanations for all of them – TanMath Dec 31 '15 at 3:03

# C (function), 51

Recursive function takes input integer as a parameter:

f(n){n>>4?f(n>>4):0;n&=15;n+=n>9?55:48;putchar(n);}


### Test driver:

#include <stdio.h>

f(n){if(n>>4)f(n>>4);n&=15;n+=n<10?48:55;putchar(n);}

int main (int argc, char **argv) {

f(15);puts("");
f(1000);puts("");
f(256);puts("");
f(0);puts("");

return 0;
}


s="0123456789ABCDEF"
(sequence(s<$s)!!)  Usage example: sequence(s<$s)!!) $1000 -> "00000000000003E8". This creates a list of all hexadecimal numbers up to 16 hex-digits. Luckily this happens in order, so we can simply pick the nth one. Edit: @Mauris squeezed out 2 bytes. Thanks! • Dat list monad doe – Daenyth Dec 31 '15 at 14:38 • @Daenyth: I've switched from Monad to Functor – nimi Jan 2 '16 at 2:46 • How about s="0123456789ABCDEF";(sequence(s<$s)!!) – Lynn Jan 2 '16 at 5:04
• @Mauris: awesome! – nimi Jan 2 '16 at 5:15

# dc, 37

?[16~rd0<m]dsmxk[A~r17*+48+Pz0<p]dspx


Recursively divmods by 16, pushing the remainder to the stack until nothing left to divide. Then print each element of the stack, using divmod by 10 to achieve A-F digits. Probably more detail tomorrow... (and hopefully less bytes).

# Python, 59 58 bytes

h=lambda i:(i>15 and h(i/16)or'')+"0123456789abcdef"[i%16]


1 byte saved by CarpetPython

Run as: print h(15)

Test it here (Ideone.com).

Explanation:

h=lambda i:                                                 # Define h as a function that takes two arguments
(i>15 and h(i/16)or'')                           # Evaluate h(i/16) if i > 15, else, give ''
+"0123456789abcdef"[i%16]  # Append (i%16)'th hexadecimal number.

• Nice work. You can also save another byte with h=lambda i:(i>15 and h(i/16)or'')+"0123456789abcdef"[i%16]. – Logic Knight Jan 1 '16 at 3:20
• Nice work indeed, you can save another two like this: h=lambda i:(i>15 and h(i/16)or'')+chr(48+i%16+i%16/10*7) – Willem Jun 20 '16 at 5:48

# C (gcc), 45 44 bytes

f(n){n&&f(n/16);n%=16;putchar(n+48+n/10*7);}


Try it online!

• In the exercise there is the phrase "•Newline not mandatory" this means that the number has to end with '\n'? – RosLuP Nov 1 '18 at 8:56

# Bash (function), 62

Thanks to @manatwork for suggesting using recursion.

h()(x=({0..9} {A..F})
echo (($1>15))&&h$[$1/16]${x[$1%16]})  • Nice. But the recursive way still seems to be shorter: h(){ x=({0..9} {A..F});echo (($1>15))&&h $[$1/16]${x[$1%16]}; } – manatwork Dec 31 '15 at 10:40
• @manatwork Nice - thanks! For some reason I usually forget to try recursion in bash, even though I'm using it in other answers. Using () instead of { ;} around the function body saves even more :) – Digital Trauma Dec 31 '15 at 16:43

# Perl 6,  53  48 bytes

{[R~] (0..9,'A'..'F').flat[($_,*div 16...^0)X%16]||0} {[R~] (0..9,'A'..'F').flat[.polymod(16 xx*)]||0} This creates a sequence of values that are Integer divided (div), until the result is 0 excluding the 0 from the sequence $_, * div 16 ...^ 0


It then crosses (X) that sequence using the modulus operator (%) with 16

( … ) X[%] 16


It uses those values as indexes into a flattened list consisting of two Ranges 0..9 and 'A'..'Z'

( 0 .. 9, 'A' .. 'Z' ).flat[ … ]


Finally it concatenates (~) them using the reverse (R) meta operator

[R[~]] …


If that results in a False value (empty string), return 0

… || 0


Usage:

# (optional) give it a lexical name for ease of use
my &code = { … }

say <15 1000 256 0>.map: &code;
# (F 3E8 100 0)

say code 10¹⁰⁰;


# MATL, 27 bytes

i16H#\wt9>?7+]wt]xN$hP48+c  This uses release 5.1.0 of the language/compiler, which is earlier than this challenge. ### Example >> matl > i16H#\wt9>?7+]wt]xN$hP48+c
>
> 1000
3E8


### Explanation

i              % input number
              % do...
16H#\        % remainder and quotient of division by 16
w            % move remainder to top of stack
t9>          % does it exceed 9?
?            % if so
7+         % add 7 (for letter ASCII code)
]            % end if
w            % move quotient back to the top
t            % duplicate
]              % ...while (duplicated) quotient is not zero
x              % delete last quotient (zero)
s/__;_;_/#/
s/__;__/@/
s/___;_/!/
s/____/)/
/[1-9_]/b
y/)!@#$%^-*(?<>:+=/0123456789ABCDEF/ s/^0*//  It's not the obvious language for this challenge, but it does have the advantage of supporting input numbers up to (depending on your implementation) between 4000 digits and the limit of your system's available (virtual) memory. I converted RSA-1024 to hex in about 0.6 seconds, so it scales reasonably well. It works using successive division by two, accumulating every 4 bits of carry into a hex digit. We use non-letter characters to represent our output, so that we always accumulate carry between the decimal input and the hex output, and convert to conventional hexadecimal at the very end. # PHP, 65 66 64+1 62 59 bytes function h($n){$n&&h($n>>4);echo"0123456789abcdef"[$n&15];}  recursive printing function, prints a leading zero (insert >16 before && to remove it) programs, 64 bytes +1 for -R (run as pipe with -nR) for(;$n=&$argn;$n>>=4)$s="0123456789abcdef"[$n&15].$s;echo$s?:0;


requires PHP 5.6 or later (5.5 cannot index string literals)

or

for(;$n=&$argn;$n>>=4)$s=(abcdef[$n%16-10]?:$n%16).$s;echo$s?:0;


requires PHP 5.6 or 7.0 (7.1 understands negative string indexes)

Run as pipe with -nR or try them online.

• I am missing a plus sign echo+$s for input 0 – Jörg Hülsermann Mar 14 '17 at 13:02 • + sign cuts the output at the first letter ... so .. ?:0 – Titus Oct 31 '18 at 23:31 # Julia, 55 bytes h(n)=(n>15?h(n÷16):"")"0123456789ABCDEF"[(i=n%16+1):i]  This is the basic recursive function implementation. It accepts an integer and returns a string. If the input is less than 15, floor divide it by 16 and recurse, otherwise take the empty string. Tack this onto the front of the appropriately selected hexadecimal character. # Pyre, 98 bytes Doing this in a language without arithmetic operators was probably a mistake. let h=def (n)(if n.gt(15)h(n.div(16).int!)else "").concat("0123456789abcdef".list!.get(n.mod(16)))  Use like this: do let h = ... print(h(15)) end  Ungolfed: let h = def (n) do if n.gt(15) let x = h(n.div(16).int!) else let x = "" x.concat("0123456789abcdef".list!.get(n.mod(16))) end  # Ruby, 48 characters (Copy of Loovjo's Python answer.) h=->n{(n>15?h[n/16]:'')+[*?0..?9,*?a..?f][n%16]}  Sample run: 2.1.5 :001 > h=->n{(n>15?h[n/16]:'')+[*?0..?9,*?a..?f][n%16]} => #<Proc:0x00000001404a38@(irb):1 (lambda)> 2.1.5 :002 > h[15] => "f" 2.1.5 :003 > h[1000] => "3e8" 2.1.5 :004 > h[256] => "100"  ## Seriously, 35 bytes ,;4ª@%)4ª@\╬Xε D@;7ªD+@9<7*+c+n  Hex Dump: 2c603b34a640252934a6405c60ce58ee204460403b37a6442b40393c372a2b632b606e  Try It Online Explanation: , Get evaluated input  ╬ Repeat the quoted function until top of stack is 0 ;4ª@% Make a copy of the number mod 16 ) Send it to bottom of stack 4ª@\ Integer divide the original copy by 16 X Delete the leftover zero. At this point the stack is the "digits" of the hex number from LSD to MSD ε Push empty string D n Essentially fold the quoted function over the stack. @; Roll up the next lowest digit, make a copy 7ªD+ Add 48 @ Bring up the other copy 9< 1 if it's at least 10, else 0 7* Multiply with 7. + Add. This will shift 58->65 and so on. c Convert to character. + Prepend to current string.  Note that the ;7ªD+@9<7*+c is equivalent to 4ª▀E, which would save 8 bytes, but I thought that perhaps a function that pushes the base b digits as a string might be considered too much of a "heaxadecimal built-in". # Javascript ES6, 64 58 bytes v=>eval('for(z="";v;v>>=4)z="0123456789ABCDEF"[v%16]+z')  Saved 6 bytes thanks to ןnɟuɐɯɹɐןoɯ and user81655. • Use eval: v=>eval('for(z="";v;v=v/16|0)z="0123456789ABCDEF"[v%16]+z') – Mama Fun Roll Dec 31 '15 at 3:53 • Oh yeah, try using atob and btoa for that long string. – Mama Fun Roll Dec 31 '15 at 4:03 • @ןnɟuɐɯɹɐןoɯ Tried v=>{for(z="";v>0;v=v/16|0)z=btoaÓ]·ã»óÐ1[v%16]+z;return z} (The double tildes are single tildes) ==> 64 chars, 71 bytes. Not worth it. – usandfriends Dec 31 '15 at 4:42 • v=v/16|0 is just a complex way of writing v>>=4. – user81655 Dec 31 '15 at 7:28 # Befunge-93, 58 &:88+%"0"+:"9"7*+\8/2/:!#|_# ,_@ >:#  First time doing a real golfing challenge in Befunge, I bet there's a one-liner for this that's shorter since all those spaces in the middle of the second line seem wasteful. You can step through it here. Partial explanation: &: Take input. :88+%: Take the remainder modulo 16. "0"+: Add it to the ASCII value of 0. :"9": If the result is greater than the ASCII value of 9... 7*+: Add 7 to convert it to a letter. \: Save the resulting character on the stack. 8/2/: Divide by 16 rounding down. :!#|_: Exit the loop if the result is 0. #: Otherwise go back to the modulus step. >:#,_@ (wrapping around): Once finished, output the stack in LIFO order. # ><>, 46 + 3 = 49 bytes This would have been shorter if ><> had integer division, which we now have to emulate by subtracting modulo 1. Still, I think this uses some pretty neat wrapping around tricks! >:?!v:f1+%:a(?v v \-%1:,+1f}+"0"<+7< !?:r/ro;  Try it online! ## Explanation First loop >:?!v:f1+%:a(?v v \-%1:,+1f}+"0"<+7<  The first loop performs the classic converting to hex algorithm. It does modulo 16 (:f1+%) and checks if the result is < 10 (:a(?). If it's not, we need to add 7 (7+) in order to go from the decimals to the capital alphabet in the ASCII table. Else, we can proceed by adding the ASCII value for 0 ("0"+) and shifting the character to be output to the bottom of the stack because we'll have to output them in reverse order. The top value is then replaced by its result of integer division by 16. This is emulated by computing a/b - (a/b)%1 (f1+,:1%-). When the loop is finished, the stack contains the hexadecimal characters in reversed output order and a 0. Second loop !?:r<ro;  The second loop reverses the list and checks if top element is 0. If it is, we know all nonzero were printed and we should terminate. Else, we output the character and reverse the list again to prepare for the next iteration. The : when entering the second loop will duplicate the 0 which has no effect. # SpecBAS - 110 bytes 1 h$="0123456789ABCDEF",r$="" 2 INPUT d 4 q=INT(d/16),r=d-(q*16),r$=h$(r+1)+r$,d=q
5 IF q>15 THEN 4
6  ?h$(q+1)+r$


This uses an algorithm I found on WikiHow (2nd method).

Strings in SpecBAS are 1-based, hence the +1 to pick out the correct element.

# C (clang), 83 bytes

f(n){char h[8]={0};int i=8;while(i>0){h[i-1]=n%16;n/=16;printf("%x",h[8-i]);i--;}}



Try it online!

Alternate solution in C

# Ruby, 40 bytes

Stolen from Inspired by manatwork's answer, but using an interesting loophole to make it shorter.

h=->n{(n>15?h[n/16]:'')+(n%16).to_s(17)}


## REXX, 80 78 bytes

arg n
h=
do while n>0
h=substr('0123456789ABCDEF',n//16+1,1)h
n=n%16
end
say h


# C, 48 bytes

h(x){x/16&&h(x/16);x%=16;putchar(x+=48+x/10*7);}


This is not completely original, I shaved 5 bytes off of the version Digital Trauma put up.

# APL(NARS), chars 34, bytes 68

{⍵≤0:,'0'⋄(∇⌊⍵÷16),(1+16∣⍵)⊃⎕D,⎕A}


test:

  g←{⍵≤0:,'0'⋄(∇⌊⍵÷16),(1+16∣⍵)⊃⎕D,⎕A}
g 0
0
g 100
064
g 1000
03E8
g 1
01
`