8

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?

Gab
  • 5,604
  • 6
  • 36
  • 52
  • 6
    There is no "byte" type in JavaScript. There are, however, "typed arrays" in very new versions of JavaScript, supported in new browsers and in V8. What you want is an "Int8Array" or a "Uint8Array". – Pointy Jun 14 '12 at 01:01
  • @Pointy do i just declare : var buf = new Int8Array() ? – Gab Jun 14 '12 at 01:05
  • @Gab http://www.khronos.org/registry/typedarray/specs/latest/ – ephemient Jun 14 '12 at 01:07
  • 1
    The typed arrays are really pretty weird; they're somewhat different from normal JavaScript arrays. – Pointy Jun 14 '12 at 01:09
  • @ephemient i am not using recent enough version of JavaScript to have any of what's described in khronos.org/registry/typedarray/specs/latest – Gab Jun 14 '12 at 13:38
  • **See Also** [How to store a byte array in Javascript](https://stackoverflow.com/q/12332002/1366033) – KyleMit Oct 31 '21 at 16:56

1 Answers1

6

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.

severeon
  • 96
  • 4