Using Javascript to incorporate a number into a UInt8Array

I need to insert a 2-byte number (ranging from 0 to 65,536) into a UInt8Array. For inserting a single byte number, I can easily refer to its index in the array like this:

let bufarray = new Uint8Array(buffer);
bufarray[0] = 1;

However, I am unsure of how to add a 2-byte number to a UInt8Array in Javascript/Typescript. Any guidance is appreciated.

Answer №1

To effectively split a two byte number into its individual bytes, bitwise shifting is required.

var originalNumber = 0xaaff;
var firstByte = ((originalNumber >> 8) & 0xff);
var secondByte = originalNumber & 0xff;
console.log(firstByte);
console.log(secondByte);

var buffer = new ArrayBuffer(2);
var Uint8View = new Uint8Array(buffer);
Uint8View[0] = firstByte;
Uint8View[1] = secondByte;

var Uint16View = new Uint16Array(buffer);
console.log(Uint16View[0]);

Answer №2

Allow the browser to handle the task on your behalf:

let array16 = new Uint16Array([49238]);
let array8 = new Uint8Array(array16.buffer);

bufarray[0] = array8[0];
bufarray[1] = array8[1];

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

Manipulate the value of an HTML element's style parameter with jQuery

How do I change an element's style property using jQuery? This is the HTML code I am working with: <div id="template" style="width:200px; height:200px; border:none;">blabla...</div> I attempted to do this: $('#template').attr ...

Unable to retrieve information from req.body, however able to retrieve data from req.params

I'm facing an issue with my code where I am not able to retrieve user data from req.body as it returns undefined. However, I can successfully access the required information from req.params. Can anyone provide guidance on how to resolve this issue? co ...

Enhance your webpage design with stylish CSS formatting using Bulma cards

My HTML output is as follows: https://i.stack.imgur.com/aBdEF.jpg It seems that the footer is not matching up with the cards... The CSS component I am using looks like this: .card-equal-height { display: flex; flex-direction: column; height: 100%; ...

Using jQuery to send data with an AJAX post request when submitting a form with

This is the code I'm working with: <html> <body> <?php include('header.php'); ?> <div class="page_rank"> <form name="search" id="searchForm" method="post"> <span class="my_up_text">ENTER THE WEBSITE TO ...

Implementing matDatePicker in Angular with real-time data binding to Firestore using [(ngModel)]

Utilizing the Real Time Database, I implemented the angular material matDatePicker to store news dates. However, after transitioning to the firestore collection, retrieving the saved date in an angular service displays it as an object: "date": { " ...

Angular implementation of a dynamic vertical full page slider similar to the one seen on www.tumblr

I'm determined to add a full-page slider to the homepage of my Angular 1.x app After testing multiple libraries, I haven't had much luck. The instructions seem incomplete and there are some bugs present. These are the libraries I've experi ...

Mastering GraphQL querying in React using TypeScript

After successfully setting up a graphql and being able to use it in Postmen, here is how it looks: query listByName($name: String!) { listByName(name: $name) { id name sortOrder } } My variable is defined as {"name&quo ...

What do you call a function that serves no purpose?

Consider a scenario where you have a function defined as: function FunctionT(){ //do something } When describing this function, would you classify it as empty, undefined, or can either term be used interchangeably? Is there a specific designation for thi ...

Utilizing jQuery's AJAX method for Access-Control-Allow-Origin

Here's the code snippet I'm working with: $.ajax({ url: url, headers: { 'Access-Control-Allow-Origin': '*' }, crossDomain: true, success: function () { alert('it works') }, erro ...

Personalized AngularJS required text

After utilizing the built-in AngularJS directive required and encountering a validation error, I receive a small popup near the field displaying "Please fill out this field". My issue lies in needing the text to be displayed in another language. How should ...

Emphasize a specific line of text within a <div> with a highlighting effect

I'm looking to achieve a similar effect as demonstrated in this fiddle As per StackOverflow guidelines, I understand that when linking to jsfiddle.net, it's required to provide some code. Below is the main function from the mentioned link, but f ...

Is it possible in Firebase to retrieve multiple queries and consolidate them into a collectionData?

In situations where the number of equalities exceeds 10, the "in" operator can be utilized. In such cases, the array can be divided into multiple sub-arrays of size 10 and multiple query requests can be initialized. When the array length is less ...

What is the best way to modify a single item within a v-for loop in Vue.js 3?

I am attempting to achieve the following: <tr v-for="item in items" :key='item'> <td v-for="field in fields" :key='field'> {{ item[field.toLowerCase()] }} </td> </tr> It seems that ...

Swapping elements with drag and drop in Angular 7

I'm experimenting with the new Angular 7 CDK Drag and drop feature to rearrange a list of items. However, I haven't been able to find an option to swap elements - most of the examples focus on sorting elements instead. Check out this example on ...

Filter out specific fields from an object when populating in MongoDB using the aggregate method

Is there a way to use the populate() function in MongoDB to exclude specific fields like email and address, and only retrieve the name? For example: const results = await Seller.aggregate(aggregatePipeline).exec(); const sellers = await Seller.populate(re ...

Angular2 encountered a TypeError stating that self._el_11 is not a valid function

Looking to attach an event listener to an input field? Check out the code snippet below: <input ref-search (keyup)="search(search.value)"> Here is the corresponding search method: search(condition: string){ console.log(condition); } When ente ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

Obtain the directory path of a node module

I am looking to retrieve specific files from an NPM package for my project. Currently, I am working with Vue and a validator, and I need to access a localization file for translation purposes. To import the validator, I have used the following standard c ...

Error message: Unable to retrieve `__WEBPACK_DEFAULT_EXPORT__` before initializing Firebase Admin in a nx and nextjs application

My current project involves a Typescript Nx + Next.js App integrated with Firebase (including Firebase Admin). In this codebase, I have defined a firebase admin util as shown below - // File ./utils/FirebaseAdmin.ts // import checkConfig from './check ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...