Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation.

For example :

65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111])
12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [0b00110000, 0b01000100])
1 142 =  Uint8Array<[4,118]> (0b0011000001000100 = [0b00000100, 0b01110110])
400 = Uint8Array<[1,144]> (0b0000000110010000 = [0b00000001, 0b10010000])
256 = Uint8Array<[1,0]> (0b0000000100000000 = [0b00000001, 0b00000000])
64 =  Uint8Array<[64]> (0b0000000001000000 = [0b01000000])
-1 = Uint8Array<[]> I do not handle negative numbers

I have been attempting to edit bytes individually as shown below:

const buffer : Uint8Array = new Uint8Array([0,0])
buffer[bytePos] &= ~(1<<bitToEdit); //to set at 0
buffer[bytePos] |= (1 <<bitToEdit) //to set at 1

The byte editing operation works, but I am unsure how to extract bytes from the number and populate them into this array.

Answer №1

To achieve this functionality, you can utilize the BigInt feature along with the modulus operator (%) and the Uint8Array.from method.

In cases involving negative numbers or when dealing with a value of 0, the code provided will result in an empty Uint8Array containing zero elements. The output of this code is in Big Endian format, similar to the example given, achieved by reversing the byte array.

function convertToByteArray(number) {
  let bigIntNumber = BigInt(number);
  let byteArrayResult = [];
  while (bigIntNumber > 0n) {
    byteArrayResult.push(Number(bigIntNumber % 0x100n));
    bigIntNumber /= 0x100n;
  }
  return Uint8Array.from(byteArrayResult.reverse());
}

console.log(convertToByteArray(
  0x01_00_00_00_00_00_00_00_03n
)) // Output: Uint8Array(9) [ 1, 0, 0, 0, 0, 0, 0, 0, 3 ]

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

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...

An issue arises when attempting to utilize URL parameters within a loader

In my React project, I am utilizing React-Router. The code for my movie page is as follows: import React from "react"; import axios from 'axios' export async function loader({ params }) { const movieId = params.movieId; const mov ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Generating a clickable link for a variable within javascript

$scope.msg = "Data Updated Successfully. Item ID: " + $scope.id; After successfully updating any data, a message will be displayed as "Data Updated Successfully. Item ID: 13456". I want to turn the ID into a clickable hyperlink. Here is what I have attem ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

How can you define the types of function arguments when destructuring arguments in TypeScript?

TS throws an error that states: Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type. Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type. Below is the function I am wor ...

Converting CSS code into JavaScript

I am currently working with the following code: .mr15 > * margin-right: 15px &:last-child margin-right: 0 I need help translating this code to Javascript. Should I use JQuery or pure Javascript for this scenario? Thank you. ...

Is it possible to incorporate an additional value into the jQuery widget 'Autocomplete' by using a second variable?

For several years, I have been utilizing the jQuery 'Autocomplete Widget' in my projects. This plugin allows me to pass a value labeled as 'term' to the PHP SQL code that works like this: $( "#cs1" ).autocomplete({ aut ...

Alias route for `src` in Ionic 3

I have set up a custom webpack configuration for Ionic 3 in order to use src as a path alias (meaning I can import from src/module/file): resolve: { alias: { 'src': path.resolve('./src') } } However, after updating to Ionic ap ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

Testing an asynchronous function in JavaScript can lead to the error message: "Have you neglected to utilize await?"

Here is an example of the code I am working with: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } = respon; myStatus = statusCode ...

Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this: <div id="catalogo" class="container"> <div class="row"> <div *ngFor="let artista of artistas" class="col-sm" style="mar ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

Trigger event once item is selected from the jQuery combobox dropdown

I have implemented a custom autocomplete combobox using the jQuery UI library to create text fields with dropdown functionality. This hybrid input allows users to either select an item from the dropdown or enter free text manually. However, I need to trigg ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

The best way to consistently execute setTimeout in order, regardless of the timing, is by utilizing a Promise

I have the following code snippet: var timeOne = new Promise(function(resolve,reject) { setTimeout(function(){ console.log('This is one'); }, Math.random() * 1000); }); var timeTwo = new Promise(function(resolve,reject) { s ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...