Converting Uint8Array to Uint32Array on the client side

I'm working with a process that returns raw binary data in the form of a Uint8Array, representing two unsigned 32-bit numbers (Uint32)...

When I log this data to the browser console:

data: Uint8Array(8) [1, 0, 0, 0, 2, 0, 0, 0]

These values correspond to two unsigned 32 bit numbers (4 bytes each)

My question is, how can I convert this binary data into JavaScript numbers?

I attempted using Uint32Array.from(x), but it resulted in an array of 8 numbers, which is incorrect.

The desired output should be an array containing just the two numbers - first 4 bytes -> 1, next 4 bytes -> 2.

Answer №1

Seems like this solution is effective:

const arr1 = new Uint8Array( [1,0,0,9, 2,0,0,9] );
const arr2 = new Uint32Array( arr1.buffer );
console.log(arr2);
const arr3 = new Uint8Array( arr2.buffer );
console.log(arr3);

Answer №2

When working with TypedArrays and ArrayBuffers, it's important to consider the byte offset when creating new views. Peter Prographo's solution may not work as expected if the TypedArray is created with a byte offset. For example:

let array8 = new Uint8Array(myArrayBuffer, 128, 16);
let array32 = new Uint32Array(array8.buffer);

In this case, the new Uint32Array will cover the entire buffer instead of just the specified range (from 128 to 144).

To address this issue, you can adjust the creation of the new view using:

let array32 = new Uint32Array(array8.buffer, array8.byteOffset, array8.byteLength / 4);

If you are working with a different TypedArray such as Uint16Array or BigUint64Array, make sure to replace the divisor 4 with the appropriate number of bytes per element for that TypedArray.

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

Steps for creating a hovering effect that overlays a circular image by 50%

I'm trying to implement a feature on my website where an overlay appears when a user hovers over their display picture. However, I'm facing a challenge as I want the overlay to only cover half of the circle, not the entire photo. After research ...

Unable to retrieve form values from a $modalInstance

When launching a $modalInstance, the user will need to select an option from dynamically loaded radio inputs and return the chosen value. To open the $modalInstance, this function is used: $scope.openAddFriendGroup = function () { var addFriendGroupMod ...

A guide on utilizing should.js to verify object equality when dealing with a property value that is NaN

It appears that there may be a bug in should.js related to the special value NaN, which is not equal to itself. ({ a: 1, c: 3, b: 2, d: NaN }).should.eql({ a: 1, c: 3, b: 2, d: NaN }); Despite the expectation that this tes ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

Complete and submit both forms during a single event

Essentially, I have an event called onclick that takes form data and stores it in a variable. When another function is executed by the user, I want to send that variable through ajax within the function. This is the onclick event (first form): $('#n ...

Arranging the y-value array based on the x array in ascending order using Python

If I have two arrays like this: x = [0, 7, 2, 4, 6, 9, 5] y = [1, 2, 3, 4, 5, 6, 7] With data points at coordinates such as [0,1], [3,2], and [x_n,y_n]. How can I organize array y so that it corresponds to an ascending order of x values? Meaning the x v ...

Modify opacity color of ImageBackground in React Native

I have been working on creating a screen as seen below: To achieve this, I have developed the following component: import React, {Component} from 'react'; import {View, Text, StyleSheet, ImageBackground, Image} from 'react-native'; im ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

Importing text data from a text file in Java or jQuery without the need for a web server

I've attempted to utilize both the jQuery.Get() and $.Get() methods for this task, but they don't seem to be working as expected. <head> <script type="text/javascript" src="jquery-2.1.3.min.js" > </script> <script lang ...

Guide on uploading a file to Amazon Glacier with Node.js

While browsing through the Amazon AWS documentation, I stumbled upon this helpful example. var glacier = new AWS.Glacier(), vaultName = 'YOUR_VAULT_NAME', buffer = new Buffer(2.5 * 1024 * 1024); // 2.5MB buffer var params = {vaultName: ...

Display images from an Array in a Java GUI application

For a programming project, I am trying to display two dice images when a button is clicked. Can someone please assist me with this task? Here is the progress I have made so far: public class Main extends Application { Button roll; Stage ...

SWR Fails to Recognize Environment Variables

I'm struggling to utilize ENV variables when using the SWR hook for data fetching. My current approach is as follows: const videoURLWithEnv = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCwkj9jcrMZCcbcIa6nF5LNQ&ma ...

What is the method for retrieving posts based on a specific userID?

I am currently developing a project that requires displaying posts from a specific user when their name is clicked by either a guest or logged-in user. This involves passing the user's ID to the URL parameters in order to retrieve all the posts posted ...

Unable to eliminate the default styling of Material UI table using an external CSS file

Currently, I am incorporating a Material Ui table into my project. My goal is to eliminate the border and adjust the padding of the table. Upon investigation, I came across a default className for material ui table known as MuiTableCell-root-40. Below is t ...

Tips for troubleshooting PHP errors while making a jQuery AJAX request

My dilemma involves an HTML form that I submit to a PHP server. When I submit the form using a standard method with a submit button and the action set to "screen_custom.php", everything works perfectly fine. I receive a page filled with valid JSON data. H ...

Free up memory in Three.js

Utilizing the shape extrusion tool within the system, I have been extruding shapes along a spline. However, I've encountered a problem where my RAM quickly becomes full every time I move the spline nodes, as I create a new mesh each time this action i ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

Enzyme in Action: Using React.js to Emulate a Click Event

I have been working on a React.js application which is a straightforward Cart app. You can take a look at the code sandbox here: https://codesandbox.io/s/znvk4p70xl The issue I'm facing is with unit testing the state of the application using Jest and ...

Displaying selected list item while concealing the original

I have a dropdown menu with several options. What I am looking for is to have it so that when we click on the drop down, a list of choices appears. Then, when we select an option from the dropdown, the original selection should be replaced with the one th ...