## DEV Community is a community of 871,998 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

bryanvieta

Posted on • Updated on

# Convert Decimal to Binary for IOT Product With Vue.js

I just made a recent Internet of things product for a company using Raspberry pi. It is a safe locker that opens with a correct decimal number. My client wanted to convert decimal to binary number and then save that to the database. When the user sends a query to change the password, the server should convert binary to decimal and show that to the user for updating.

I have used Bcrypt earlier but this was a new experience for me. However, I managed to find a code to convert decimal to binary online but I have to make many changes in the code to make it work correctly for the bigger numbers.

For this app, I used Vue.js in the front-end and Node.js for the back-end and IOT connection. Most of the code is Vanilla.js. Vue.js and Node.js are for just a few operations.

For the decimal to binary and again binary to decimal conversion, I have used Vue.js and axios to send data to the back-end. Here is the code:

Decimal to binary code:

``````var xx = document.getElementById("input").value;
var xy = parseInt(xx);
var xz = xy.toString(2);
document.getElementById("demo").innerHTML = xz;
``````

I found the above code online, this code returns the correct answer only for 16 characters long input. In case, you insert an input that is longer than 16 characters then you get the wrong answer.

To solve this problem, I used Bignumber.js. This is a great Javascript library to perform the arithmetic operations more precisely. To get the correct answers for more than 16 characters, you need to use Bignumber.js. Here is the code:

Vue.js Code with Bignumber.js:

``````dectobin() {
var x = new BigNumber(this.text_value, 10)
var dectobin = x.toString(2);
this.ans = dectobin;
},
``````

In the above code, dectobin() function is called at the click event on the button. Apart from that, this.text_value is used to get the value from the user input. toString is an in-built javascript function to get the binary value of a number.

Vue.js code for binary to decimal:

``````bintodec() {
var cc = new BigNumber(this.text_value, 2);
this.ans = cc;
},
``````

Just like the above operation, bintodec() function is also called at the click event from the user. Again, text_value is the value updated by the user.

So, above is the simple code for decimal to binary conversion. I spend almost one day to understand the concept of bignumber and binary numbers. If you are also dealing with such numbers then I hope this code helps you! Demo