Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a byte array in Javascript

I'm going to be storing a large array of byte values (most likely over a million) in Javascript. If I use a normal array with normal numbers, that will take 8 MB, because numbers are stored as IEEE doubles, but if I can store it as bytes, it will be only 1 MB.

I'd like to avoid wasting that much space for obvious reasons. Is there a way to store bytes as bytes instead of doubles? Browser compatibility isn't an issue for me, as long as it works in Chrome. This is in HTML5, if that makes a difference.

like image 896
Kendall Frey Avatar asked Sep 08 '12 15:09

Kendall Frey


People also ask

What is byte array in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

What does byte array store?

QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings. Using QByteArray is much more convenient than using const char * .

Is ArrayBuffer same as buffer?

1. A Buffer is just a view for looking into an ArrayBuffer . A Buffer , in fact, is a FastBuffer , which extends (inherits from) Uint8Array , which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer .

Does JavaScript have a byte type?

There is no byte predefined type in javascript. Show activity on this post. JavaScript now supports raw binary data types (byte).


2 Answers

By using typed arrays, you can store arrays of these types:

Type Value Range Size(bytes)
Int8Array -128 to 127 1
Uint8Array 0 to 255 1
Uint8ClampedArray 0 to 255 1
Int16Array -32768 to 32767 2
Uint16Array 0 to 65535 2
Int32Array -2147483648 to 2147483647 4
Uint32Array 0 to 4294967295 4
Float32Array -3.4E38 to 3.4E38 4
Float64Array -1.8E308 to 1.8E308 8
BigInt64Array -2^63 to 2^63 - 1 8
BigUint64Array 0 to 2^64 - 1 8

Demo in Stack Snippets & JSFiddle

var array = new Uint8Array(100); array[42] = 10; console.log(array[42]);
like image 68
Kendall Frey Avatar answered Sep 19 '22 00:09

Kendall Frey


var array = new Uint8Array(100);     array[10] = 256; array[10] === 0 // true 

I verified in firefox and chrome, its really an array of bytes :

var array = new Uint8Array(1024*1024*50);  // allocates 50MBytes 
like image 40
reuns Avatar answered Sep 18 '22 00:09

reuns