Convert to Hexadecimal
Challenge
Write a program that takes in a number greater than or equal to 0 and outputs its representation in hexadecimal (base 16).
Examples
0 => 0
1 => 1
10 => A
15 => F
16 => 10
107 => 6B
153 => 99
207 => CF
1000 => 3E8
10381 => 288D
48821 => BEB5
Rules
- No built-in hexadecimal functions.
- More generally, any base conversion function is considered to be disallowed.
- Letters can be uppercase or lowercase.
- It should work at least for all inputs greater than 0 up to the language's default type limit.
- Leading zeros in the output is fine. (i.e.
000003E8
for 32-bit numbers) - This is [code-golf], so shortest code wins.
2 answers
Vyxal, 24 bytes
16ʀẋfÞ×'ẏ16$e*∑?=;hṘk6i∑
All this when just H
, 16R
, or even k6τ
would have sufficed.
Times out for every input > 100
Explained
16ʀẋfÞ×'ẏ16$e*∑?=;hṘk6i∑
16ʀẋ # Repeat the range [0, 16) (input) times.
f # And flatten into a single list.
Þ× # Get every possible combination with repetition of all possible lengths.
# (This is why it times out for large inputs)
# (Because it needs to be long enough to have the correct output in theory)
' ; # Keep combinations where:
ẏ16$e*∑ # (x_0 * 16 ^ 0) + (x_1 * 16 ^ 1) + (x_2 * 16 ^ 2) + ...
= # equals
? # the input
h # Get the first combination
k6i # And get the corresponding characters in the string "0123456789ABCDEF"
∑ # Join into a single string
💎
Created with the help of Luminespire.
Lean 4, 103 100 95 bytes
It WOULD be 96 bytes, except there are 4 extra bytes of data that the 2 (two) unprintable characters take up. :( Nevermind, I managed to save 5 bytes from something else. :D
def h(i:Nat):String:=if i<16then s!"{"0123456789ABCDEF".get ⟨i⟩}"else(h (i/16))++(h (i%16))
I actually am not sure how this even works, lol. I had thought of wrapping the string indice part in a s!""
string (similar to Python's f
-strings) to try and avoid (...).toString
, and it's nice to see that Lean 4 actually automatically interprets a Char
object inside a String
as a String
object lol.
Only 93 more bytes until I beat the Vyxal solution xD
Hexdump since this contains unprintable characters:
00000000 64 65 66 20 68 28 69 3a 4e 61 74 29 3a 53 74 72 |def h(i:Nat):Str|
00000010 69 6e 67 3a 3d 69 66 20 69 3c 31 36 74 68 65 6e |ing:=if i<16then|
00000020 20 73 21 22 7b 22 30 31 32 33 34 35 36 37 38 39 | s!"{"0123456789|
00000030 41 42 43 44 45 46 22 2e 67 65 74 20 e2 9f a8 69 |ABCDEF".get ...i|
00000040 e2 9f a9 7d 22 65 6c 73 65 28 68 20 28 69 2f 31 |...}"else(h (i/1|
00000050 36 29 29 2b 2b 28 68 20 28 69 25 31 36 29 29 |6))++(h (i%16))|
2 comment threads