I can not found a way to change a value in an ArrayBuffer.
I am able to print the content of an ArrayBuffer by using a TextDecoder. When printing the buffer there is a string. I want to change one char on the string by editing one byte on the buffer. I was able to access one byte on the buffer by converting it to an Int8Array but I am not sure on how to converting it again to an ArrayBuffer after editing the byte
var enc = new TextDecoder("utf-8");
console.log('ArrayBuffer string content : ', enc.decode(data));
let view = new Int8Array(data);
view[56] = 48;
view[57] = 48;
// Convert view again to an ArrayBuffer
//console.log('ArrayBuffer string new content : ', enc.decode(data));
You can use the set method on your Int8Array directly :
var enc = new TextDecoder("utf-8");
console.log('ArrayBuffer string content : ', enc.decode(data));
let view = new Int8Array(data);
view.set([48], 56);
view.set([48], 57);
As stated in the top answer:
var enc = new TextDecoder("utf-8");
console.log('ArrayBuffer string content : ', enc.decode(data));
let view = new Int8Array(data);
view.set([48], 56);
view.set([48], 57);
It actually does change the byte value in the data variable.
I spend the last couple of hours trying to figure out how to do this, myself.
Then I finally understood that when you create the new Int8Array(), you're not creating a copy of the data - you're just creating a different type of pointer to it.
It's messy, it's confusing, but it works.
Cheers!
Related
the question says it all, im receiving a base64 encoded ZIPFILE from the server, which I first want to decode to a ZIPFILE in memory and then get the ZIPFILES content, which is a json-file.
I tried to use JSZIP but im totally lost in this case ... the base64 string is received with javascript by a promise.
So my question in short is: How can I convert a base64 encoded ZIPFILE to a ZIPFILE in memory to get its contents.
BASE64 -> ZIPFILE -> CONTENT
I use this complicated process to save much space on my database. And I dont want to handle this process on server-side, but on clientside with JS.
Thanks in advance!
If anyone is interested in my solution to this problem read my answer right here:
I received the data in a base64-string format, then converted the string to a blob. Then I used the blob-handle to load the zipfile with the JSZip-Library. After that I could just grab the contents of the zipfile. Code is below:
function base64ToBlob(base64) {
let binaryString = window.atob(base64);
let binaryLen = binaryString.length;
let ab = new ArrayBuffer(binaryLen);
let ia = new Uint8Array(ab);
for (let i = 0; i < binaryLen; i++) {
ia[i] = binaryString.charCodeAt(i);
}
let bb = new Blob([ab]);
bb.lastModifiedDate = new Date();
bb.name = "archive.zip";
bb.type = "zip";
return bb;
}
To get the contents of the zipfile:
let blob = base64ToBlob(resolved);
let zip = new JSZip();
zip.loadAsync(blob).then(function(zip) {
zip.file("archived.json").async("string").then(function (content) {
console.log(content);
// content is the file as a string
});
}).catch((e) => {
});
As you can see, first the blob is created from the base64-string. Then the handle is given over to the JSZip loadAsync method. After that you have to set the name of the file which you want to retrieve from the zipfile. In this case it is the file called "archived.json". Now because of the async("string") function the file (file contents) are returned as a string. To further use the extracted string, just work with the content variable.
I use emscripten compile the c code into asm.js
my c code like this:
int _call_main(char* p, int number)//p is the start arrary, number is the lengh
I want to send a bytearray data to the c code, My Js code like this:
var decode_encode_audio = Module.cwrap('_call_main', 'number', ['array','number']);
........
var byteArray = new Uint8Array(message.data);//audio data
var offset = Module._malloc(70000);
Module.HEAP8.set(byteArray, offset);
decode_encode_audio(offset , byteArray.length);
In the C code, I print the point p array, I got a messed data, the start part and the end part of p is correct(I save the file), However, In the middle part is messed.I replace the function(Module.HEAP8.set) with [Module.HEAPU8.set],also got error. I don't know why?
I change the Js code :
var decode_encode_audio = Module.cwrap('_call_main', 'number', ['number','number']);//not array
........
var byteArray = new Uint8Array(message.data);//audio data
//var offset = Module._malloc(70000);
//Module.HEAP8.set(byteArray, offset);
decode_encode_audio(byteArray, byteArray.length);
I can get correct data.
Can anyone tell me what's wrong with "Module.HEAP8.set" method.
You are writing unsigned data from your Uint8Array into the signed view HEAP8. You should use the HEAPU8, which is used for unsigned data.
I want convert an integer (signed) to 32 bit (big endian) into a octet stream and give the octet stream as a array value to the constructor of a
Buffer Object.
I can create it in the console for example for the value -2000:
<code>
buf = Buffer(4)
buf.writeInt32BE(-2000)
buf // is <Buffer ff ff f8 30>
buf1 = new Buffer([0xff, 0xff, 0xf8, 0x30])
</code>
The value -3000 is for example -3000 : 0xff ,0xff, 0xf4, 0x48
But the framework i use accepts not the writeInt32BE function and throws exception.
How can i convert a 32 bit integer value signed to a octet Array stream without the writeInt32BE ?
A function that takes a value and returns an array of octet stream.
Using a 4 byte array buffer, converted to a data view and calling setInt32 on the view seems to work. This approach supports specification of both little endian and big endian (the default) formats independent of machine architecture.
function bigEnd32( value) {
var buf = new ArrayBuffer(4);
var view = new DataView(buf);
view.setInt32( 0, value);
return view;
}
// quick test (in a browser)
var n = prompt("Signed 32: ");
var view = bigEnd32( +n);
for(var i = 0 ; i < 4; ++i)
console.log(view.getUint8( i));
Documentation was located searching for "MDN ArrayBuffer" "MDN Dataview" etc. Check out DataView in detail for properties that access the underlying array buffer - you may be able to tweak the code to suite your application.
I want to convert a float value like 26,4 into a byte array. Something like: [51,51,-45,65]. Another example: 32,2 > [-51, -52, 0, 66].
I can do it in Arduino C++ and Python, but I don't see how to do it in JavaScript.
I have an input field in my HTML page where I want to write my float value and decode it before sending it to a Python script.
Is it possible?
Typed Arrays
First create a Float32Array which is a view on top of an actual byte-buffer (ArrayBuffer). We can allocate the buffer and view in a single operation:
var farr = new Float32Array(2); // two indexes each 4 bytes
Store the floating point numbers. These will be stored in IEEE-754 format:
farr[0] = 26.4;
farr[1] = 32.2;
Now we can add another view for the underlying buffer, this time signed 8-bit view:
var barr = new Int8Array(farr.buffer); // use the buffer of Float32Array view
console.log(barr);
// -> 51,51,-45,65,-51,-52,0,66
Live demo below
var farr = new Float32Array(2); // two indexes each 4 bytes
farr[0] = 26.4;
farr[1] = 32.2;
var barr = new Int8Array(farr.buffer); // use the buffer of Float32Array view
console.log(barr);
document.querySelector("div").innerHTML = barr[0]+","+barr[1]+","+barr[2]+","+barr[3]+","+barr[4]+","+barr[5]+","+barr[6]+","+barr[7];
<div></div>
I have a program which reads an array of bytes. Those bytes are supposed to be ISO-8859-2 decimal codes of characters. My test array has two elements: 103 which is letter g and 179 which is letter ł (l with tail). I then create a Blob object from it and check its content using two methods:
FileReader
objectURL
The first method gives correct results but the second method gives an extra character in the saved blob file.
Here is the code:
var bytes = [103, 179];
var chr1 = String.fromCharCode(bytes[0]);
var chr2 = String.fromCharCode(bytes[1]);
var str = '';
str += chr1;
str += chr2;
console.log(str.charCodeAt(0)); //103
console.log(str.charCodeAt(1)); //179
console.log(str.charCodeAt(2)); //NaN
var blob = new Blob([str]);
console.log(blob.size); //3
//Checking Blob contents using first method - FileReader
var reader = new FileReader();
reader.addEventListener("loadend", function() {
var str1 = this.result;
console.log(str1); //g³
console.log(str1.charCodeAt(0)); //103
console.log(str1.charCodeAt(1)); //179
console.log(str1.charCodeAt(2)); //NaN
});
reader.readAsText(blob);
//Checking Blob contents using second method - objectURL
var url = URL.createObjectURL(blob);
$('<a>',{
text: 'Download the blob',
title: 'Download',
href: url
}).appendTo('#my');
In order to use the second method I created a fiddle. In the fiddle, when you click the "Download" link and save and then open the file in a binary editor, it consists of the following bytes: 103, 194, 179.
My question is, where does the 194 come from and how to create a blob file (using the createobjectURL method) containing only bytes given in the original array ([103, 179] in this case).
The extra 194 comes from an encoding issue :
179 is the unicode code point of "SUPERCRIPT THREE" so the string str will contains "g³". After creating the blob, you will get this string encoded in utf8 : 0x67 for g, 0xC2 0xB3 for ³ (194, 179 in decimal) and it takes 3 bytes. Of course, if you use a FileReader, you will get back 2 characters, "g³".
To avoid that situation (and if you don't want to put everything in utf8), you can use a typed array to construct the blob :
var u8 = new Uint8Array(bytes);
var blob = new Blob([u8]);
That way, you will keep exactly the bytes you want.