23
\$\begingroup\$

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!
\$\endgroup\$
  • \$\begingroup\$ First problem, hope you guys enjoy! \$\endgroup\$ – Random Guy Dec 31 '15 at 2:06
  • 5
    \$\begingroup\$ Are leading zeros allowed in the output, e.g for 32bit numbers 000003E8? \$\endgroup\$ – nimi Dec 31 '15 at 3:03
  • \$\begingroup\$ Any limit on the input? \$\endgroup\$ – Loovjo Dec 31 '15 at 3:27
  • 1
    \$\begingroup\$ @nimi Yes, that is allowed. \$\endgroup\$ – Random Guy Dec 31 '15 at 6:08
  • 1
    \$\begingroup\$ Fun fact: C++ has a hex builtin. \$\endgroup\$ – Matthew Roh Mar 14 '17 at 17:10

32 Answers 32

0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.