"JavaScript: Issue Encountered While Converting Hexadecimal to Decimal

I've been working on a custom function to convert hexadecimal to decimal in my Scratch project:

function Hex2Decimal(hex){
    var deci = 0;
    var num = 1;
    var hexstr = String(hex);
    hexstr = hexstr.toLowerCase();
    var expon = 0;
    for(var i = 0; i < hex.length; i++){
        expon = Math.pow(16,hexstr.length - (num+1));
        if(hexstr[num+1] === "a"){
            deci = (10*expon)+deci;
        }else if(hexstr[num-1] === "b"){
            deci = (11*expon)+deci;
        }else if(hexstr[num-1] === "c"){
            deci = (12*expon)+deci;
        }else if(hexstr[num-1] === "d"){
            deci = (13*expon)+deci;
        }else if(hexstr[num-1] === "e"){
            deci = (14*expon)+deci;
        }else if(hexstr[num-1] === "f"){
            deci = (15*expon)+deci;
        }else if(hexstr[num-1] != "undefined"){
            deci = (Number(hexstr[num-1])*expon)+deci;
        }
        num = num + 1;
    }
    return deci;
}

However, I'm encountering an issue when inputting "BC324240." The function returns '197338148' instead of '3157410368.' Converting the result back to hex gives 'BC32424,' where the final '0' is being ignored for some reason that I'd appreciate help identifying. I also noticed that using '10' as input returns 1...

Answer №1

If you're looking to convert a hexadecimal string to a decimal number, this built-in function can help:

dec = parseInt('0x' + hexstr,16);

Just make sure that the number being converted is within the maximum safe JavaScript integer range:
(2^53 - 1) = 0x1fffffffffffff = 9007199254740991.

For larger numbers, check out this code snippet:
Please note I didn't create this code, so I might not be able to explain it in detail.

Answer №2

The final position (the number you need to multiply by 16^0) is not included in your calculation because of this line:

exponent = Math.pow(16, hexstr.length - (num+1));

This code is incorrect and should be changed to:

exponent = Math.pow(16, hexstr.length - num);

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

Issue encountered when attempting to modify the directive when the drop-down list is changed in AngularJS

Experiencing issues updating the directive when the drop down list is changed using AngularJS. Below is my application code: HTML Code <div ng-app="myApp" ng-controller="MyCtrl"> <select ng-model="opt" ng-options="font.title for font in font ...

What is the method for invoking a JSON web service with jQuery that necessitates basic authentication?

My knowledge of javascript is limited, but I am attempting to access a JSON web service that requires basic authentication using jQuery. Unfortunately, my searches on Google have not yielded any useful results. Can anyone tell me if what I am trying to a ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

What is the best way to change an object into a string in node.js?

Recently, I've delved into the world of node js and I'm eager to create a basic coap client and server using this technology. Successfully, I managed to set up a server hosting a text file, but now I aim to access it from the client. var coap = ...

How can I get my view to render in node.js/express using XMLHttpRequest()?

After working on my node/express app for the past three days, I am still facing an issue with making a GET request to a specific route from the client side. Despite using XMLHttpRequest and setting the necessary headers for authorization, the app remains s ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Removing an item from JSON data using Node.js and Express

Currently, I am attempting to remove an entry from json data. In order to view the data, I utilize the following: app.route('/data/:id') .get((req:Request, res: Response) => { let id = req.params.id; res.status(200).send(projects ...

The returned JSON object lacks a specified name

After receiving the JSON data from the server, I noticed an unnamed node within the 'someStuff' object: { "someStuff": { "": { "foo": 0 }, "moreStuff": { "foo": 2 } } } This raises ...

Implementing Jquery to Repurpose a Function Numerous Times Using a Single Dynamic Value

Important: I have provided a functional example of the page on my website, currently only functioning for the DayZ section. Check it out here Update: Below is the HTML code for the redditHeader click event <div class="redditHeader grey3"> & ...

Issue Arising from Printing a Custom Instruction in a Schema Generated Document

When dynamically adding a directive, the directive is correctly generated in the output schema. However, it seems to be missing when applied to specific fields. Here is how the directive was created: const limitDirective = new graphql.GraphQLDirective({ na ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

The Gatsby plugin image is encountering an error due to a property that it cannot read, specifically 'startsWith

While browsing the site, I couldn't find a solution to my issue, but I stumbled upon an open bug on Github. The only workaround mentioned at the moment is to utilize GatsbyImage. As I delve into converting a Gatsby project from version 2 to 3, I have ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Retrieving the chosen option from a radio button

<!DOCTYPE html> <html> <body> <input type="radio" name="colors" value="red" id="myRadio">Red color <p>Click the "Try it" button to display the value of the value attribute of the radio button.</p> <button onclick=" ...