The objective of this esp32 tutorial is to explain how to convert a number to string in different bases, using the Espruino on the ESP32. The tests were performed using a DFRobot’s ESP32 module device integrated in a ESP32 development board.
Introduction
The objective of this post is to explain how to convert a number to string in different bases, using the Espruino on the ESP32.
To perform the mentioned conversion, we simply need to call the JavaScript toString method on the number we want to convert, passing as input the base we want to use [1]. The base is represented as a number, with its value corresponding to the desired base.
If we don’t pass any input to the toString function, the decimal representation (base 10) will be used [1].
Although the most used bases alternative to decimal are binary, octal and hexadecimal, we can use other ones.
The tests shown in this ESP32 JavaScript tutorial were performed using a DFRobot’s ESP32 module device integrated in a ESP32 development board.
The code
The code for this tutorial will be very simple. In this case, instead of writing a full script and upload it to the ESP32 like we have been doing in previous tutorials, we will send the commands directly on the command line interface of the Espruino IDE.
We will start by declaring a number variable and then print it in different bases and compare the results against this online base converter. I will use the number 34, but you can use other numbers to test.
var num = 34;
We will first call the toString method without any arguments, so the conversion is performed to decimal representation.
console.log(num.toString());
Next we will convert it to binary, which is the same as base 2. From the online converter, the expected result is 100010.
console.log(num.toString(2));
You can check below at figure 1 the result of the command, which matches the previously mentioned value obtained from the online tool.
Figure 1 – Conversion of number to string in binary.
Now we will use a base 8 representation. The result should be 42, as obtained from the online converter tool.
console.log(num.toString(8));
At figure 2 you can see the result from the previous command, which matches the expected result.
Figure 2 – Conversion of number to string in octal.
We will test it for hexadecimal representation, which corresponds to base 16. The expected result is 22.
console.log(num.toString(16));
As can be seen in figure 3, the result matches again the expected value.
Figure 3 – Conversion of number to string in hexadecimal.
To finish, we will use base 20, which is not a base commonly used. The expected value for this base is 1e.
console.log(num.toString(20));
As can be seen in figure 4, the value printed to the console is the one expected.
Figure 4 – Conversion of number to string in base 20.