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:
Understand the problem
Make a plan
Execute the plan
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
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
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
The next step is to divide:
2047 / 16 = 127
Our quotient is 127
, so we repeat the operations above:
127 % 16 = 15
Our remainder is again 15
, so we add F
to our hexadecimal string, giving us:
FF
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
Our remainder is 7
, so we add it to our hexadecimal string, giving us:
7FF
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
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('');
}
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))
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('');
}
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('');
}
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);
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
π― Give yourself an A. Grab your copy of A is for Algorithms
Top comments (1)
And now call your function to convert 1234 to base 20 ;)