Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an array of byte in Javascript

Tags:

javascript

I am doing server-side javascript and i need to have a typed array of byte of a certain size. I tried :

var buf = [1024]; (guives me Cannot convert org.mozilla.javascript.NativeArray@1e565bd to byte[] error)
var buf = byte[1024]; (wrong synthax)

What is the synthax?

like image 395
Gab Avatar asked Jun 14 '12 00:06

Gab


1 Answers

This depends on which server-side JavaScript package you use. Different packages implement different flavors of JavaScript and different versions of ECMAScript.

In NodeJS v0.6.x you have access to typed arrays. Creating one of these arrays is fairly trivial.

// creating an array of bytes, with 1024 elements
var bytes = new Uint8Array(1024);

There are other typed arrays available, handling 16 bit and 32 bit integers.

// creating an array of 16 bit integers, with 128 elements
var array_16bit = new Uint16Array(128);

// creating an array of 32 bit integers, with 16 elements
var array_32bit = new Uint32Array(16);

When using typed arrays, there are a few things to keep in mind. Typed arrays do not inherit the standard array prototype, and these arrays have an immutable length.

like image 137
severeon Avatar answered Nov 03 '22 19:11

severeon