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

Is it feasible to choose the component generated by this element?

My current dilemma involves a component that renders a form, however, it also has its own form "catcher". var FormUpload = React.createClass({ submit : function(){ var formdata =new FormData(); ...

Guide on how to bundle a TypeScript project into a single JavaScript file for smooth browser integration

I am currently working on a small project that requires me to write a JavaScript SDK. My initial plan was to create a TypeScript project and compile it into a single JavaScript file, allowing users of my SDK to easily inject that file into their web pages. ...

The function ng-click does not successfully uncheck ion-radio

In the process of developing my application using the ionic framework, I encountered a challenge where I needed to deselect an ion-radio button when clicking on an input tag. Despite attempting to achieve this functionality through this ionic play link, I ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Anti-virus programs are preventing long-standing AJAX connections

Hey there, I have come across something quite strange while developing a web application that relies on long-held HTTP connections using COMET to stream data between the server and the application. The issue I've encountered is that some anti-virus p ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Tips on how to automatically resize the browser window to a specific width and height once it has been minimized

If a JSP page is minimized onload, we need to find a way to restore it through a JavaScript call. Are there any other methods available for achieving this? The restoration should be to the height and width selected by the user. I have attempted the followi ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

Discover various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities. Although things are running smoothly, I am faci ...

What are the steps for creating a dropdown menu that allows for easy selection of the correct item

I am dealing with a dropdown menu as shown below. <select name="slt"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Three +</option&g ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

State not getting updated with array passed to this.setState()

Within an array, I have stored the following credentials: //The Snippet variable is an array that looks like this { details: test, _id: "5d9d0b506ee7d03a54d8b1f6", name: "TEST GREEN", content: "<div style="background-color:green; height:100px; widt ...

Tips for validating and narrowing a type in TypeScript using isNull instead of isNonNullable

I want to implement a universal type guard for entities returned from an API. The goal is to handle any null | undefined values by throwing an HttpStatus.NOT_FOUND error. Initially, I tried the following approach: export const entityOr404 = <T>(entit ...

What role does the sequence play in matrix transitions that involve rotating and translating simultaneously?

Attempting to animate a matrix3d with both rotation and translation concurrently has yielded unexpected results for me. It seems that changing the order of applying rotation and translation produces vastly different outcomes. http://jsfiddle.net/wetlip/2n ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

Sort through object attributes according to a different object

I have two sets of data represented by objects object_a and object_b. I want to extract the items from object_a that correspond to the IDs found in object_b. const object_a = { 100: "Stack Overflow", 101: "MDN Web Docks", 10 ...

Input Error in ASP.NET JavaScript

Within my ASP.NET website, I have implemented an <asp:TextBox /> where the text input is encoded using HttpUtility.HtmlEncode(); Furthermore, the page is equipped with validation controls like <asp:RequiredFieldValidator /> and <asp:CustomV ...

Having difficulties in properly connecting faces while UV mapping a cube in Three.js

After successfully applying an image texture to a cube through UV mapping for a photo-sphere viewer, I noticed that thin straight lines are visible where the faces of the cube join. Interestingly, this issue does not occur when splitting texture tiles via ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

Invoking an asynchronous method of the superclass from within an asynchronous method in the subclass

I'm currently developing JavaScript code using ECMAScript 6 and I'm facing an issue with calling an asynchronous method from a superclass within a method of an extending class. Here is the scenario I'm dealing with: class SuperClass { c ...