Transforming a decimal number into binary base 2 manually in Javascript without using pre-defined functions

As a newcomer to coding and Javascript, I have been given an assignment that requires me to convert base 10 numbers to binary without using specific built-in methods in Javascript (such as alert(a.toString(16))). The constraints are that I can only use loops, arrays, and functions. Here is what I have so far:

var number = prompt("Enter an unsigned base 10 number");
    if (number>=0) {
        var base = prompt("Enter b for binary, o for octal, or h for hexadecimal");

        if (base=="h"||base=="H") {
            ;
        }

It's clear that I don't have much to work with at the moment. I am wondering about the equation or formula I should use to perform the conversion from base 10 to binary. Also, I'm unsure of how to handle representing A=10, B=11, C=12, and so on for a hexadecimal base. Any guidance you can provide would be greatly appreciated!

Answer №1

update: I recently learned a more efficient method from Alnitak (refer to the discussion below). This approach may seem complex, but it ultimately simplifies the process, eliminating the need for unnecessary steps.

Summary:

To convert a decimal number like 10 into binary, we utilize the formula 2^n where n is determined so that 2^n remains less than 10. For example, 2^3 = 8 (a valid choice), while 2^4 = 16 exceeds 10. Therefore, we mark 2^3 with a value of 1 at index 3 in an array.

We then proceed to calculate the remainder as 10-2^3, resulting in 2. We repeat this process until the difference reaches zero.

Finally, after completing all computations, we reverse the array since the sequence needs to be flipped.

var num = prompt("Please input a positive integer in base 10");
var binaryArr = [];
var i = 0;

function decToBinConverter(x) {
  powerOfTwo = Math.pow(2, i);
  if (powerOfTwo < x) {
    binaryArr[i] = 0;
    i++;
    decToBinConverter(x);
  }  else if (powerOfTwo > x) {
    i--;
    updatedX = (x - Math.pow(2, i));
    binaryArr[i] = 1;
    i = 0;
    decToBinConverter(updatedX)
  } else if (powerOfTwo == x) {
    binaryArr[i] = 1;
    result = binaryArr.reverse().join(); 
  }
  return result;
}

var binaryResult = decToBinConverter(num); // store the final result in binaryResult

document.write(binaryResult);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to determine when AJAX-loaded content has completely loaded all of its images?

After making an AJAX request to load HTML, it includes img tags within it. I am in need of a way to detect when these images have finished loading so that I can adjust the container size accordingly. Since I do not know how many images will be present in ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

Sending a jQuery variable to an external PHP script

Utilizing the HTML5 Geolocation API, I am able to retrieve latitude and longitude coordinates which I then need to pass to an external PHP file. This PHP file (getPosition.php) retrieves JSON variables from my database, allowing me to utilize them in geo.j ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

Steps to initiate a slideUp animation on a div using jQuery

Is there a way to make a div slide up from the bottom of the page to cover 30% of the screen when a user clicks a button, and then slide back down when the button is clicked again? Any suggestions on how I can achieve this? Thank you! EDIT 1) $(document ...

Tips for incorporating a custom CSS design into a jQueryUI tooltip

I am struggling to apply my custom CSS class on top of the jQueryUI tooltip. Although the tooltip is displaying correctly, my styles are not being applied. Here is the code I'm using: $(document).ready(function () { $("#roles").tooltip({ content: ...

Creating a digital item in a nested category using Mogoose

Within the realm of mongoose, there exists an object by the name of 'target' which houses an image (consisting of a name and extension). Each individual 'target' object also possesses a sub-collection of other objects, each containing t ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Is there a way to manually stop a file upload (stream) using a XMLHttpRequest on the server?

Utilizing XMLHttpRequest (Level 2) to transfer a file to a node.js server, I am currently examining the file-stream for valid headers on the server side. The goal now is to halt the upload if any errors are encountered during streaming. My XMLHttpRequest c ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Consecutive pair of XMLHttpRequest requests

Is it possible to create a functionality where the page index.php sends a Javascript variable called idToken, which is then received in another page called token.php using Javascript as well? In the token.php page, there will be more code that processes ...

The functionality of the click and mousedown events seems to be disabled when using an Ajax form

Trying to create a simple Ajax popup featuring a form with 3 data fields and a submit button, however I'm unable to trigger the submit button programmatically. jQuery('#FormSubmit').click() seems to have no effect. The same goes for jQuer ...

ReactJS encountered an error of type ERR_INVALID_ARG_TYPE

Hello there! I recently purchased a template from ThemeForest and everything was working perfectly with the previous version. However, upon updating to the new version, I encountered an error that looks like this: > TypeError [ERR_INVALID_ARG_TYPE]: Th ...

Tips for retrieving data using ajax with servlets:

I am trying to send some data on the page to a servlet So I have created the following jQuery code to achieve this I am using all the data to construct a JSON string and send it directly to the servlet However, I am unsure how to retrieve the entire dat ...