DEV Community

Cover image for How to Convert Decimal to Hexadecimal in JavaScript and Python
Jared Nielsen
Jared Nielsen

Posted on • Originally published at jarednielsen.com

How to Convert Decimal to Hexadecimal in JavaScript and Python

If you want to learn how to code, you need to learn algorithms. Learning algorithms improves your problem solving skills by revealing design patterns in programming. In this tutorial, you will learn how to convert numbers from decimal to hexadecimal in JavaScript and Python.

This article originally published at jarednielsen.com

How to Code a Decimal To Hexadecimal Algorithm

Programming is problem solving. There are four steps we need to take to solve any programming problem:

  1. Understand the problem

  2. Make a plan

  3. Execute the plan

  4. Evaluate the plan

Understand the Problem

To understand our problem, we first need to define it. Let’s reframe the problem as acceptance criteria:

GIVEN a decimal
WHEN I pass it to a function
THEN the function returns the hexadecimal equivalent
Enter fullscreen mode Exit fullscreen mode

That’s our general outline. We know our input conditions (a decimal) and our output requirements (a hexadecimal equivalent value), and our goal is to perform the conversion of the decimal to hexadecimal.

Let’s make a plan!

Make a Plan

Let’s revisit our computational thinking heuristics as they will aid and guide is in making a plan. They are:

  • Decomposition

  • Pattern recognition

  • Abstraction

  • Algorithm

If converting a decimal to binary is simply a process of repeatedly dividing the decimal by 2 and using the remainder to build a string, how do you think we convert a decimal to any base?

We divide the decimal by the base!

Let's break that question down into smaller questions.

What is a number?

It's a symbol representing a value.

What is 1?

A symbol representing the value one.

What is 'one'?

A symbol representing the value 1. (And round and round we go...)

What is 10?

In the decimal, or base-10, numeral system, it's a value represented by two symbols. Because it's two symbols, we can't use it in base-16. What's the solution? More symbols!

Hexadecimal, or base-16, uses the first six characters of the Roman alphabet to represent the values of 10 through 15.

Decimal Hexadecimal
10 A
11 B
12 C
13 D
14 E
15 F

If we wanted to create our own base, say, Emojidecimal, we could use whatever symbols we want:

Decimal Hexadecimal
10 🍎
11 🍌
12 🐈
13 πŸ•
14 🐘
15 🦊

The symbol doesn't matter, as long as we all agree on the value that it represents. Do you think Emojidecimal will gain traction? πŸ€”

Let's convert 2047 to hexadecimal. The first step is to get the remainder of our dividend and divisor.

2047 % 16 = 15
Enter fullscreen mode Exit fullscreen mode

Our remainder is 15, but we are no longer using base-10, so we can't add this value to our hexadecimal string. If we use the table we created above, we can see that 15 maps to F, so we start building our hexadecimal string with it, giving us:

F
Enter fullscreen mode Exit fullscreen mode

The next step is to divide:

2047 / 16 = 127
Enter fullscreen mode Exit fullscreen mode

Our quotient is 127, so we repeat the operations above:

127 % 16 = 15
Enter fullscreen mode Exit fullscreen mode

Our remainder is again 15, so we add F to our hexadecimal string, giving us:

FF
Enter fullscreen mode Exit fullscreen mode

We then divide 127 / 16. Our quotient is 7, so we calculate the remainder and divide 7 by 16:

7 % 16 = 7
7 / 16 < 0
Enter fullscreen mode Exit fullscreen mode

Our remainder is 7, so we add it to our hexadecimal string, giving us:

7FF
Enter fullscreen mode Exit fullscreen mode
INPUT NUM

SET digits TO "0123456789ABCDEF"

SET result TO AN EMPTY STRING

WHILE num IS GREATER THAN 0
  GET VALUE OF num MOD 16
  PREPEND result WITH CORRESPONDING VALUE IN digits
  REASSIGN num THE FLOOR VALUE OF decimal DIVIDED BY 2

OUTPUT result
Enter fullscreen mode Exit fullscreen mode

Execute the Plan

Now it's simply a matter of translating our pseudocode into syntax. Let's start with JavaScript.

How to Code Decimal to Hexadecimal Conversion in JavaScript

Rather than prepending each remainder, we instead concatenate the result string and use a combination of string and array methods to split the string into array items, reverse the order of the array, and then join the items in a string.

const decimalToHex = (num) => {

  const digits = '0123456789ABCDEF';

  let result = '';

  while (num > 0) {
    result += digits[num % 16];
    num = Math.floor(num / 16);
  }

  return result.split('').reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

How to Code Decimal to Hexadecimal Conversion in Python

def decimal_hexadecimal(num):
    digits = '0123456789ABCDEF'

    result = ''

    while num > 0:
        result += digits[num % 16]
        num = num // 16

    return ''.join(reversed(result))

Enter fullscreen mode Exit fullscreen mode

Evaluate the Plan

Let's take another look at our JavaScript above. We could modify that function to accept any base, not just 16.

const decimalToBase = (num, base) => {

  const digits = '0123456789ABCDEF';

  let result = '';

  while (num > 0) {
    result += digits[num % base];
    num = Math.floor(num / base);
  }

  return result.split('').reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

The split() method converts the string to an array, so we could just start with an array instead and use unshift() rather than reverse() (J4F):

const decimalToBase = (num, base) => {

  const digits = '0123456789ABCDEF';

  let result = [];

  while (num > 0) {
    result.unshift(digits[num % base]);
    num = Math.floor(num / base);
  }

  return result.join('');
}
Enter fullscreen mode Exit fullscreen mode

Or we could just cheat and use the built-in toString() method and pass it 2 as an argument, meaning we want to convert our string to binary:

const decimalToBase = (num, base) => num.toString(base);
Enter fullscreen mode Exit fullscreen mode

We could make the same optimizations in our Python function, or we could use built-in hex() method.

But what fun is that?

A is for Algorithms

Image description
πŸ’― Give yourself an A. Grab your copy of A is for Algorithms

Top comments (1)

Collapse
 
patricktingen profile image
Patrick Tingen

And now call your function to convert 1234 to base 20 ;)