How to convert a 4-bit byte array into an integer using JavaScript

Utilizing web sockets, I transmit a 4-bit byte array to my JavaScript library. This byte array signifies a number that I want to retrieve back, all within JavaScript. Examples abound for reading a byte array into a string, but finding examples for the reverse scenario has proven challenging.

In my C# code:

    public static void SendImage(byte[] blobArray,
        byte[] imageArray , string ts)
    {
        var blobSize = BitConverter.GetBytes(blobArray.Length);
        var tsHdr = Encoding.ASCII.GetBytes(ts);
        byte[] newPacket = new byte[imageArray.Length + tsHdr.Length + blobArray.Length+4];
        Buffer.BlockCopy(tsHdr, 0, newPacket, 0, tsHdr.Length);
        Buffer.BlockCopy(blobSize, 0, newPacket, 17, 4);
        Buffer.BlockCopy(blobArray, 0, newPacket, tsHdr.Length+4, blobArray.Length);
        Buffer.BlockCopy(imageArray, 0, newPacket, tsHdr.Length+4+ blobArray.Length, imageArray.Length);

     }

This process passes a timestamp (using 17 bits), followed by 4 bits for the length of the first image. Subsequently, the first image is included, followed by the second image.

To retrieve all this in JavaScript:

ws.onmessage = function (e) {
        try {
                var ts = String.fromCharCode.apply(String, new Uint8Array(e.data, 0, 17));
                var year = ts.substr(0, 4);
                var month = ts.substr(4, 2);
                var day = ts.substr(6, 2);
                var hour = ts.substr(8, 2);
                var min = ts.substr(10, 2);
                var second = ts.substr(12, 2);
                var mil = ts.substr(14, 3);

                liveTimeStamp = hour + "-" + min + "-" + second + "-" + mil + "  " + day + "/" + month + "/" + year;
                var blobLen= e.data.slice(17, 4);
                vat img1 = 'data:image/jpeg;base64,' + arrayBufferToBase64(e.data.slice(21, blobLen ));
               var img2 = "data:image/jpeg;base64," + arrayBufferToBase64(e.data.slice(21 + blobLen, len - blobLen + 21)); 
    };

Answer №1

To extract a Uint32 from your Uint8Array in JavaScript, assuming the C# code is generating little-endian data, you can use a DataView like this:

var data = new Uint8Array(e.data);
var dataView = new DataView(data.buffer);
var blobLen = dataView.getUint32(17, true); // false for big-endian

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

Deactivate the backface culling feature when loading an imported .obj file in three.js

I'm struggling with disabling wireframe rendering on the rear side of my vehicle. Any ideas on how to deactivate backface culling in wireframe mode for three.js? Check out this link for a helpful image ...

Incorporate user input into Alert Dialog Boxes

Would you be able to assist me in displaying the input value from the "email" field in my alert box? The code seems to be working fine, but I'm having trouble getting the alert box to show the email form value. I decided to use Bootstrap for som ...

Creating a live child component using React

My issue lies with the menu component, which is supposed to dynamically load elements in another container component. Unfortunately, the child elements are not being rendered. App.js import React, { Component } from 'react'; import './App. ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

I am attempting to create a password validation system without the need for a database, using only a single

Help Needed: Trying to Create a Password Validation Website <script language="Javascript"> function checkPassword(x){ if (x == "HI"){ alert("Just Press Ok to Continue..."); } else { alert("Nope... not gonna happen"); } } ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Is there a way to determine if a website is utilizing javascript?

Currently, I am in the process of developing a web scraping tool using beautifulsoup. Some of the websites I am targeting contain JavaScript elements that prevent me from using urllib3 efficiently. As a workaround, I have incorporated selenium into my sc ...

When a parameter is passed into a React-Query function with an undefined value, it can lead to the API returning a 404 error

Two parameters are sent from the frontend to trigger a GET request in another TypeScript file. It seems that one of the parameters is not successfully passed due to unknown rerenders, resulting in a 404 Error being returned by the API call in the console. ...

How can I implement a jQuery modal dialog that loads a form page with pre-existing jQuery code for Autocomplete functionality?

I am facing an issue where I have a dynamically generated form on a web page and I want to display it using the jQuery UI modal dialog. Previously, I was suggested a solution that worked when my form did not already contain jQuery UI components like Autoc ...

Utilizing JQuery AJAX to Submit a JSONP Form with File Attachments

I have been working on implementing a contact form for our clients who create websites with their own domains through us. As part of our services, we provide hosting and a web editor to help them build their websites. The contact form they include on their ...

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

Avoid displaying "undefined" on HTML page when Firebase database value is empty

I am trying my best to explain my issue, although I struggle with scripts. Please bear with me and help me improve. ˆˆ Below is the script I am working on. The goal is to display all records with a date set for 'today or in the future'. Progr ...

Linking this to a function that takes in arguments

I am currently working with an event handler that calls a fat arrow function to execute a specific method. import React, { Component } from 'react'; class App extends Component { sayHi = msg => { console.log(msg); }; render() { ...

Trouble with displaying a cube from Blender to Three.js

Hey everyone, I'm having some trouble exporting a cube from Blender to three.js. I've exported the JSON file, but when I try to display the cube in my code, it's not showing up - instead, all I see is the setColor screen and I can't fig ...

What is the best way to connect objects that have been separated?

Looking for a way to reattach my detached objects and wondering how to replace the function that currently only triggers an alert. Any suggestions or help is appreciated. http://jsfiddle.net/jy2Zj/ In addition, I have another question - is there a method ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Spring MVC: Incorporating Java Map into Optgroup Options

In my Spring MVC project, I am currently passing a Map from Java to my webpage using the variable "userLocales" through request.setAttribute('userLocales', bluh bluh bluh). I am looking for a way to extract the strings from this variable and use ...

Leveraging scanner-js within an Angular2 environment

Exploring ways to incorporate Scanner-JS into my Angular2 project, a tool I discovered while tinkering with the framework. Being a novice in Angular2, this question might be elementary for some. I successfully installed scanner-js via npm npm install sc ...