The objective of this post 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 ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.
The objective of this post is to explain how to convert a number to string in different bases, using the Espruino on the ESP32.
If we don’t pass any input to the toString function, the decimal representation (base 10) will be used .
Although the most used bases alternative to decimal are binary, octal and hexadecimal, we can use other ones.
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.
Next we will convert it to binary, which is the same as base 2. From the online converter, the expected result is 100010.
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.
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.
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.
As can be seen in figure 4, the value printed to the console is the one expected.
Figure 3 – Conversion of number to string in base 20.