Using web sockets I send a 4 bit byte array to my JS library. This byte array represents a number and I want to read that number back but all in JavaScript. I have found plenty of examples doing the opposite and example of reading a byte array into a string.
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 pass a timestamp (taking 17 bits). Then 4 bits for the len of the 1st image. Then the image itself. Then the second image.
So, reading it all back in from JS:
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));
};
Assuming that your C# code is generating little-endian data, you should be able to extract a Uint32
from your Uint8Array
using the DataView
type like this:
var data = new Uint8Array(e.data);
var dataView = new DataView(data.buffer);
var blobLen = dataView.getUint32(17, true); // false for big-endian
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.