JavaScript Conversion from Binary to Decimal

This code is meant to convert a binary string ("100101") to its decimal equivalent. I am struggling to identify the issue causing it to not work properly. Any assistance would be greatly appreciated.

function BinaryConverter(str) { 
 var num=str.split("");
 var powers=[];
 var sum=0;
  for(var i=0;i<num.length;i++){
   powers.push(i);
}
 for(var i=powers.length-1;i>=0;i--){
  for(var j=0;j<num.length;i++){
   sum+=Math.pow(2,i)*num[j];
  }
 }
 return sum;
};

Below is my revised code. For an input of "011", it is intended to compute (2^2*0 +2^1*1 +2^0*1) which should be 3, but currently, it outputs 14. Can anyone pinpoint where I've made a mistake?

function BinaryConverter(str) { 
 var num=str.split("");
 var powers=[];
 var sum=0;
 for(var i=0;i<num.length;i++){
   powers.push(i);
 }
 for(var i=powers.length-1;i>=0;i--){
  for(var j=0;j<num.length;j++){
   sum+=Math.pow(2,i)*num[j];
  }
 }
 return sum;
};

Answer №1

An issue arises with the two nested for loops in your code. The first loop subtracts an i, while the second loop adds an i, resulting in an endless loop.

Your revised code should look like this:

function BinaryConverter(str) { 
    var num = str.split("");
    var powers = [];
    var sum = 0;
    var numlength = num.length;

    for (var i = 0; i < num.length; i++) {
        powers.push(i);
    }

    for (var i = powers.length - 1; i >= 0; i--) {
        sum += Math.pow(2, i) * num[numlength - i - 1];
    }

    return sum;
};

It seems that eliminating the nested for loop would be a better approach.

Answer №2

Instead of using parseInt() to convert binary strings, you can implement a more efficient solution without relying on Math.pow() for each digit:

function parseBinary(str) {
  var i, value = 0;
  for (i = 0; i < str.length; ++i)
    value = value * 2 + +str[i];
  return value;
}

It's important to note that this function does not validate input strings for invalid binary characters.

Answer №3

ace040686 made a minor adjustment in his answer, where he reversed the order of pow(2,i) and num[len-1-i]. Other than that, the answer is correct. Additionally, adding 0..str.length-1 to powers is unnecessary as these are implicit indices.

function convertNaive(str) {
  var num = str.split("");
  var len = num.length;
  var sum = 0;
  for(var i = len - 1; i >= 0; --i)
    sum += Math.pow(2, len - 1 - i) * num[i];
  return sum;
}

You can optimize this further to remove the unnecessary array and reduce the usage of Math.pow:

function convertImproved(str) {
  var len = str.length;
  var sum = 0;
  for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
    sum += fac * str[len - 1 - i];
  return sum;
}

Give it a try yourself:

var input = "100101";
var logNode = document.getElementById("log");

function log(line) {
  var text = document.createTextNode(line);
  var node = document.createElement("p");
  node.appendChild(text);
  logNode.appendChild(node);
}

function convertNaive(str) {
  var num = str.split("");
  var len = num.length;
  var sum = 0;
  for(var i = len - 1; i >= 0; --i)
    sum += Math.pow(2, len - 1 - i) * num[i];
  return sum;
}

function convertImproved(str) {
  var len = str.length;
  var sum = 0;
  for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
    sum += fac * str[len - 1 - i];
  return sum;
}

log("input: " + input);
log("parseInt(input, 2): " + parseInt(input, 2));
log("convertNaive(input): " + convertNaive(input));
log("convertImproved(input): " + convertImproved(input));
<div id="log" />

Answer №4

Check out this straightforward Javascript code for converting binary numbers to decimal.

run();

function run() {
    let binaryInput = 10000100111;
    let decimalOutput = convertBinaryToDecimal(binaryInput);
    console.log(decimalOutput);
}

function convertBinaryToDecimal(input) {
    let binaryString = input.toString();
    let result = 0;
    let exponent = 1;
    let currentBit = 0;
    for (let i = binaryString.length - 1; i >= 0; i--) {
        currentBit = parseInt(binaryString[i]);
        currentBit *= exponent;
        result += currentBit;
        exponent *= 2;
    }
    return result;
}

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

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...

Bizarre symbols observed while extracting data from HTML tables produced by Javascript

I am in the process of extracting data from Specifically, my focus is on the "tournament-page-data-results" div within the source code. Upon inspecting the HTML source code, the data does show up, but it appears with a mix of real information and random c ...

Are the props.children handled differently within the <Route> component compared to other React components?

Each and every react component undergoes a process in the following function, which is located in ReactElement.js within node_modules: ReactElement.createElement = function (type, config, children){ . . . } This function also encompasses <Rou ...

Calculating the subtotal amount using Vue.js is a straightforward process

My Vue.js project functions as a shopping cart, and I am looking to calculate the subtotal for each product row. Here is an excerpt of my HTML code: <div id="app"> <table border="1"> <thead> <tr> <th>#</th ...

Maximum opacity in Three.js fog

My Current Endeavor: I am in the process of developing a lightweight GIS application with topography. One feature I want to implement is atmosphere haze. The Code I'm Working With: (Please bear with me as I have multiple scenes) fogColor = new T ...

Determine the exact location of a click within an SVG element

This block of HTML includes SVG elements: <div class="container"> <div class="spacer"></div> <svg> <g id="polygonGroup" transform="translate(80, 50)"> <polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"&g ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

Show automatically created forms alongside each other within a v-for loop

When generating dynamic forms from a json file, the forms end up being displayed one on top of the other like this: https://i.sstatic.net/tbdzs.png However, I want them to be displayed like this (for example, if there are 3 inputs, the fourth one should ...

Utilizing a backup system to store environment variables within a configuration file

Currently, I am utilizing my environment variables by directly referencing process.env.NODE_ENV throughout my application. While this method works, it is becoming challenging to manage and keep track of. Therefore, I would like to consolidate all these var ...

Node responds with a 404 error upon receiving the post request

I am facing an issue with my jQuery code. Here is what I have: $.ajax( { type: 'POST', data : mydata, url : '/routerfunction', dataType : 'String', success : function(data) ...

Tips for repairing texture distortion on rounded corner surfaces in the three.js library

I managed to create a unique rounded corner plane by combining circle and plane geometries in my project. While the flat color in the rendered version looks great, I noticed that the textured part seems to get distorted and chopped up. If you want to tak ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

Activate dynamic validation to ensure all necessary fields are completed before proceeding without the need to save

Is there a way to display the standard error message that appears next to required fields upon saving a form, without actually saving it? ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below: EventBus.$on and EventBus.$emit('call ...

How do we handle the reception of document.form.submit() in the code behind?

I have a JavaScript function document.form1.submit() and I am wondering how to receive it in the code behind. In which class and method should I be looking? I need to get the value from a textbox and store it in session, but I'm not sure if I need an ...

I'm intrigued by this maneuver, but I am uncertain about its safety when used in JavaScript

I am currently contemplating the safety and reliability of assigning a variable within an if statement across different browsers. If it proves to be safe, then I am inclined to proceed with its usage. The scenario involves reading the query string and che ...

What could be the reason that a basic click function fails to locate the selector?

I have created a quick JavaScript module that opens an image and fades out a container to reveal the image. The HTML markup for the image looks like this: <div style="margin-bottom:1px;" class="rsNavItem rsThumb front"> <di ...