Convert a binary array into a signed 64-bit integer

Although JavaScript may not accurately represent all 64-bit integer numbers, it can handle numbers larger than 32 bits, which is what I am looking for. I need JavaScript to provide me with whatever level of precision it can offer.

I have a byte array of a specified length, ranging from 1 to 16 bytes, containing either a signed or unsigned integer in big-endian format (network byte order).

How can I extract the numerical value from this byte array?

Existing solutions often fail when dealing with negative numbers, and tools like DataView are limited to 32 bits. I am seeking an elegant, simple, and efficient pure JavaScript solution to address this issue. Unfortunately, I have not found a suitable solution within the visible web resources.

For reference, here is my implementation for handling positive numbers:

function readInt(array) {
    var value = 0;
    for (var i = array.length - 1; i >= 0; i--) {
        value = (value * 256) + array[i];
    }
    return value;
}

Answer №1

Take a look at this website for a clear and efficient solution:

  • Start by adding all the bits from the right side, up to the second most significant bit.
  • Remember to treat the most significant bit as -2^i instead of 2^i.

In my implementation, the code deals with a broader context involving an array and a specific position for reading.

byteArray (a Uint8Array) and utilizes the position to keep track of the next index to read from. It starts reading at the current position and updates the position as it processes each of the length bytes.

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

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Ways to manage an element that has been loaded using the load query function

After implementing the query load function to update posts on the homepage, I was able to display the most up-to-date posts. However, a new issue arose: Whenever I updated all posts without refreshing the entire page, I needed a way to control the element ...

Reactjs: Prop Type Error - Issue with retrieving the values from props during data submission

Currently, I am developing a social app where users can post screams, like posts, and add comments. The issue I'm encountering is that I am not receiving the props value when posting a new scream initially, but after refreshing the page, everything wo ...

Stop objects from shifting while easily applying a border

I have a code that adds a red border around elements when you mouseover them and removes it when you mouseout. However, the elements jump around when the border is added because it changes their dimensions. Is there a way to stop this jumping behavior? ...

How can one retrieve a file in Silverlight without using Webclient?

I'm faced with a challenging task of downloading one file into a ByteArray, editing the ByteArray, simultaneously downloading another large file, merging the first edited file into it on-the-fly, and playing it using MediaElement. Although I can down ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

Avoid excessive clicking on a button that initiates an ajax request to prevent spamming

When using two buttons to adjust the quantity of a product and update the price on a digital receipt via ajax, there is an issue when users spam the buttons. The quantity displayed in the input box does not always match what appears on the receipt. For in ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

Avoid clicking on the HTML element based on the variable's current value

Within my component, I have a clickable div that triggers a function called todo when the div is clicked: <div @click="todo()"></div> In addition, there is a global variable in this component named price. I am looking to make the af ...

In Chrome, the `Jquery $('input[name=""]').change(function will not be triggered unless there is an unhandled error following it

Here is a script that I've created to make certain inputs dependent on the selection of a radio button. The 'parent' input in this case is determined by the radio button choice. Upon document load, the script initially hides parent divs of ...

Ways to check for child items in a JSON object

My Angular-built menu uses JSON and spans up to 3 levels deep. Some items have no children, while others go further down the hierarchy. I'm trying to determine if a selected subcategory has child elements in order to hide a button. Each time a subcat ...

"Placement of script tag within the body and the function of the appendChild method

What do you think will happen in the example provided below? The majority of current browsers (such as Firefox 5, Chrome 14, Opera 11.50) will place the iframe above the text. Is this behavior standardized or just a common practice that could potentially ...

The JavaScript counterpart to jQuery's click event handler

I'm trying to figure out how to achieve the same effect as this jQuery code. var divQuery = $('.html5gallery-thumbs-0').children(); divQuery.on('click', function () {...} I attempted it like this: var divQuery = document.g ...

Trigger event listener of AngularJS directive on click and send information to it

During my exploration of AngularJS directives, I encountered a task that required me to activate the directive's listener upon clicking a button and passing data from the controller to it. Sample Directive app.directive('graphVisualization&apos ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

adding the authentication token to the Dropzone configuration for headers

I am tasked with including the header access token. $scope.dropzoneConfig = { 'options': { // passed into the Dropzone constructor 'url': 'SOME API URL' + $scope.SOME_ID }, 'eventHandlers': { ...

Efficiently Incorporating JavaScript Variables into DataTable's aoData

I am facing an issue with a variable named search_gen, which is generated through an ajax request (shown below). var search_gen; $.ajax({ type: "POST", url: link+module_name+'search_generator/'+module_active, dataType: "text", as ...