Java byteArray equivalent in JavaScript

13.5k views Asked by At

I am trying to determine what encoding scheme will give me the numbers -1 or -40 (the starting numbers for the file) for a jpeg file type.

A rest api I'm working on is expecting a byte array that looks like [-1, 94, 43, 34, etc]. In node.js I can have the byte array as hex, or any other encoding type, but I seem not able to get -1 or -40 for the starting value whichever encoding scheme I try.

In the documentation I saw an example in Java which uses the "toByteArray()" function, which seems to get the starting values (-1 or -40). Can anyone help me?

4

There are 4 answers

4
zlumer On BEST ANSWER

If I correctly understand your question, you can use Buffer to get file contents, then read the bytes from it into your array.

Java byte type is a signed 8-bit integer, the equivalent in Node.js Buffer is buf.readInt8().

So you can read the required amount of bytes from Buffer into your array using buf.readInt8()

Or just convert it into Int8Array:

new Int8Array(new Buffer([100, 200, 255, 1, 32]));
0
Alex Taylor On

You're looking for Buffer. It allows reading/writing of variously sized binary values and random access.

0
Dickens A S On

I would recommend you to change the logic of identifying a JPEG file using magic numbers from the first 4 bytes, your -40 logic could be insufficient.

FFD8FFE0 should be the first 4 bytes of a jpeg file

Therefore following Node.js program could be helpful

var fs = require('fs');
fs.open("c:\\aa1.jpg", 'r', function(err, doc){
    var check = "FFD8FFE0";
    var headerLength = ( check.length / 2 );

    var byteBuffer = new Buffer(headerLength);
    for(var i=0;i<headerLength;i++)
      byteBuffer[i] = 0x00;

    var head = "";

    fs.read(doc, byteBuffer, 0, headerLength, 0, function(err, num) {
      for(var i=0;i<headerLength;i++)
        head += byteBuffer[i].toString(16);

      if(head.toLowerCase() == check.toLowerCase())
        console.log('It is a JPEG file');
      else
        console.log('It is not a JPEG file');
    });
});

check for err and doc null check is not included in this program

Refer How to identify contents of a byte[] is a jpeg?

0
KyleMit On

You can also use TypeArray.from() method on all Typed Arrays to convert between normal arrays:

const values = [-1, 94, 43, 34]

const byteArr = Int8Array.from(values)
const original = Array.from(byteArr)

console.log({ byteArr, original })

Bonus: This works in node and also the browser