Convert a number to Hexadecimal

23

4

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!

Random Guy

Posted 2015-12-31T02:04:58.617

Reputation: 375

First problem, hope you guys enjoy! – Random Guy – 2015-12-31T02:06:02.597

5Are leading zeros allowed in the output, e.g for 32bit numbers 000003E8? – nimi – 2015-12-31T03:03:06.410

Any limit on the input? – Loovjo – 2015-12-31T03:27:11.720

@Loovjo No, it should work for any arbitrarily large number. – Random Guy – 2015-12-31T06:06:36.533

@RandomGuy Even if it exceeds the language's default number type limit? – Loovjo – 2015-12-31T06:07:35.267

1@nimi Yes, that is allowed. – Random Guy – 2015-12-31T06:08:03.220

@Loovjo No, then you can be safe. – Random Guy – 2015-12-31T06:08:33.480

@RandomGuy "No, it should work for any arbitrarily large number." ... please add this requirement to the challenge definition or drop it... having said this only in a comment sure will not be seen by everyone... – None – 2015-12-31T08:24:24.050

@yeti It is now fixed! – Random Guy – 2015-12-31T16:41:19.470

@RandomGuy ... "up to language's default type limit" ... aaaahhhh... now it reads mostly harmless ... ;-) – None – 2015-12-31T17:13:11.020

What about general base conversion built-ins, like APL's ? In my answer I use APL's which (among other usages) converts from other bases to base 10... Is that acceptable?

– Adám – 2015-12-31T20:21:34.577

@NBZ I will allow conversions to other bases, yes. – Random Guy – 2016-01-02T23:37:37.140

1Fun fact: C++ has a hex builtin. – Matthew Roh – 2017-03-14T17:10:07.320

In the exercise there is the phrase "•Newline not mandatory" this means that the number, or the hex characters that are printed have to end with '\n' a new line ? – RosLuP – 2018-11-01T08:58:23.523

Answers

4

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

Adám

Posted 2015-12-31T02:04:58.617

Reputation: 37 779

Isn't this 17 chars and around 23 bytes? – Julie Pelletier – 2016-06-18T23:00:07.127

1@JuliePelletier No, Dyalog APL uses its own 256 character codepage. – Adám – 2016-06-18T23:00:49.580

Oh! Good to know. – Julie Pelletier – 2016-06-18T23:02:13.390

14

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.

SuperJedi224

Posted 2015-12-31T02:04:58.617

Reputation: 11 342

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 – 2018-10-31T16:58:36.180

@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 – 2018-10-31T21:44:05.553

@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 – 2018-10-31T22:01:49.840

probably not. Seemed close for high values though. I know nothing about it and was attempting to see patterns. – Magic Octopus Urn – 2018-11-01T13:35:38.987

9

Java, 92 89 bytes

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

SuperJedi224

Posted 2015-12-31T02:04:58.617

Reputation: 11 342

9

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.

Loovjo

Posted 2015-12-31T02:04:58.617

Reputation: 7 357

Use binary AND. i&15 will automatically convert to integer, dropping decimals. No need of ~~ – edc65 – 2015-12-31T13:43:27.087

I saved 3 bytes and one leading zero: h=i=>i&&h(i>>4)+"0123456789abcdef"[i&15] – Neil – 2016-01-01T21:01:14.767

8

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.

Dennis

Posted 2015-12-31T02:04:58.617

Reputation: 196 637

5Same byte count: ri{Gmd_9>7*sc+\}h;]W% – Martin Ender – 2015-12-31T16:28:55.120

6

Pyth, 33 26 21 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.

Luke

Posted 2015-12-31T02:04:58.617

Reputation: 5 091

Can you add an explanation? – TanMath – 2015-12-31T02:53:57.413

Sure, which one are you interested in? – Luke – 2015-12-31T03:02:19.097

The most intersting answer! ;) it doesn't matter...Although it is a good idea to post explanations for all of them – TanMath – 2015-12-31T03:03:19.857

5

Haskell, 59 58 43 41 39 bytes

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!

nimi

Posted 2015-12-31T02:04:58.617

Reputation: 34 639

Dat list monad doe – Daenyth – 2015-12-31T14:38:31.427

@Daenyth: I've switched from Monad to Functor – nimi – 2016-01-02T02:46:45.230

How about s="0123456789ABCDEF";(sequence(s<$s)!!) – Lynn – 2016-01-02T05:04:01.663

@Mauris: awesome! – nimi – 2016-01-02T05:15:42.443

5

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;
}

Digital Trauma

Posted 2015-12-31T02:04:58.617

Reputation: 64 644

4

C (gcc), 45 44 bytes

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

Try it online!

ceilingcat

Posted 2015-12-31T02:04:58.617

Reputation: 5 503

In the exercise there is the phrase "•Newline not mandatory" this means that the number has to end with '\n'? – RosLuP – 2018-11-01T08:56:25.633

4

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.

Loovjo

Posted 2015-12-31T02:04:58.617

Reputation: 7 357

1Nice work. You can also save another byte with h=lambda i:(i>15 and h(i/16)or'')+"0123456789abcdef"[i%16]. – Logic Knight – 2016-01-01T03:20:31.917

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 – 2016-06-20T05:48:25.087

4

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

Digital Trauma

Posted 2015-12-31T02:04:58.617

Reputation: 64 644

3

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]})

Digital Trauma

Posted 2015-12-31T02:04:58.617

Reputation: 64 644

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 – 2015-12-31T10:40:14.577

1@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 – 2015-12-31T16:43:54.537

3

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¹⁰⁰;
# 1249AD2594C37CEB0B2784C4CE0BF38ACE408E211A7CAAB24308A82E8F10000000000000000000000000

Brad Gilbert b2gills

Posted 2015-12-31T02:04:58.617

Reputation: 12 713

2

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.

Titus

Posted 2015-12-31T02:04:58.617

Reputation: 13 814

1I am missing a plus sign echo+$s for input 0 – Jörg Hülsermann – 2017-03-14T13:02:55.717

+ sign cuts the output at the first letter ... so .. ?:0 – Titus – 2018-10-31T23:31:02.050

2

MATL, 27 bytes

i`16H#\wt9>?7+]wt]xN$hP48+c

This uses release 5.1.0 of the language/compiler, which is earlier than this challenge.

Example

>> matl
 > i`16H#\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)
N$h            % create vector of all remainders 
P              % flip vector
48+c           % add 48 and convert to char (will be implicitly displayed)

Luis Mendo

Posted 2015-12-31T02:04:58.617

Reputation: 87 464

2

, 31 chars / 62 bytes

↺a=⬯;ï;ï≫4@a=⩥ḊĀⒸª⩥⁽ṁṇ⸩⨝[ï%Ḑ]+a

Try it here (Firefox only).

Okay, I figured out some more stuff that golfed it down.

Explanation

It's essentially the same solution as @SuperJedi224's ES6 solution - but with something different.

See ⩥ḊĀⒸª⩥⁽ṁṇ⸩⨝? That's a really fancy way of writing "0123456789ABCDEF". ⩥Ḋ creates a range from 0 to 10, Ⓒª⩥⁽ṁṇ⸩ creates a range from 65 to 71 and converts it to a string of ASCII, and Ā...⨝ concatenates the two ranges and joins them into one string. This was probably the coolest part of my solution.

Bonus non-competitive version, 24 chars / 45 bytes

↺;ï;ï≫4@ᵴ=(⩥Ḋ⨝+ᶐ)[ï%Ḑ]+ᵴ

I decided to add an alphabet string, like in Pyth.

Mama Fun Roll

Posted 2015-12-31T02:04:58.617

Reputation: 7 234

2

sed, 341 bytes

:
s/\b/_/2
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
s/;_;_;_;_/=/
s/;_;_;__/+/
s/;_;__;_/:/
s/;_;___/>/
s/;__;_;_/</
s/;__;__/?/
s/;___;_/(/
s/;____/*/
s/_;_;_;_/-/
s/_;_;__/^/
s/_;__;_/%/
s/_;___/$/
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.

Toby Speight

Posted 2015-12-31T02:04:58.617

Reputation: 5 058

1

><>, 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.

PidgeyUsedGust

Posted 2015-12-31T02:04:58.617

Reputation: 631

1

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.

SuperJedi224

Posted 2015-12-31T02:04:58.617

Reputation: 11 342

1Use eval: v=>eval('for(z="";v;v=v/16|0)z="0123456789ABCDEF"[v%16]+z') – Mama Fun Roll – 2015-12-31T03:53:43.127

1Oh yeah, try using atob and btoa for that long string. – Mama Fun Roll – 2015-12-31T04:03:08.967

@ן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 – 2015-12-31T04:42:36.520

1v=v/16|0 is just a complex way of writing v>>=4. – user81655 – 2015-12-31T07:28:44.057

1

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.

Alex A.

Posted 2015-12-31T02:04:58.617

Reputation: 23 761

1

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

Tuomas Laakkonen

Posted 2015-12-31T02:04:58.617

Reputation: 341

1

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" 

manatwork

Posted 2015-12-31T02:04:58.617

Reputation: 17 865

1

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.

histocrat

Posted 2015-12-31T02:04:58.617

Reputation: 20 600

1

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

quintopia

Posted 2015-12-31T02:04:58.617

Reputation: 3 899

0

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

Abel Tom

Posted 2015-12-31T02:04:58.617

Reputation: 1 150

0

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)}

G B

Posted 2015-12-31T02:04:58.617

Reputation: 11 099

0

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

idrougge

Posted 2015-12-31T02:04:58.617

Reputation: 641

0

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.

Bijan

Posted 2015-12-31T02:04:58.617

Reputation: 781

0

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

RosLuP

Posted 2015-12-31T02:04:58.617

Reputation: 3 036

0

Charcoal, 25 bytes

Nθ≔⁺⭆χι…α⁶ηP0Wθ«←§ηθ≧÷¹⁶θ

Try it online! Link is to verbose version of code. Explanation:

Nθ

Input the number.

≔⁺⭆χι…α⁶η

Create the string of hexadecimal digits by joining the range 0..9 with the first six letters.

P0

Output a zero in case the input is zero.

Wθ«

Repeat while the number is nonzero.

←§ηθ

Cyclically index into the hex digits and move the cursor to the left after printing.

≧÷¹⁶θ

Integer divide the number by 16.

Neil

Posted 2015-12-31T02:04:58.617

Reputation: 95 035

0

Retina 0.8.2, 56 bytes

.+
$*#;
+`(#+)\1{15}
$1;
(#{10})?(#*);
$1$.2
T`#d`_L`#+.

Try it online! Link includes test cases. Retina doesn't actually have a built-in for this anyway. Explanation:

.+
$*#;

Convert the input to unary using #s and append a ;.

+`(#+)\1{15}
$1;

Keep trying to divide the input by 16, leaving the remainder after another ;.

(#{10})?(#*);
$1$.2

Convert each remainder to base 10, but if it's 10 or more, then just convert the last digit, leaving the 10 #s behind.

T`#d`_L`#+.

Change the digits after #s from 0-5 to A-F and delete the #s.

Neil

Posted 2015-12-31T02:04:58.617

Reputation: 95 035

0

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.

Brian

Posted 2015-12-31T02:04:58.617

Reputation: 1 209