Java byteArray equivalent in JavaScript
I am trying to figure out which encoding scheme will give me the numbers -1 or -40 (starting numbers for a file) for a jpeg file type.
The rest of the api I'm working on expects a byte array that looks like [-1, 94, 43, 34, etc.]. In node.js, I can have a byte array as hex or any other encoding type, but I can't seem to get -1 or -40 for the initial value, whatever encoding scheme I try.
In the documentation, I saw an example in Java that uses the "toByteArray ()" function that seems to get initial values โโ(-1 or -40). Can anyone help me?
source to share
If I understand your question correctly, you can use Buffer
to get the content of a file and then read bytes from it into your array.
The Java type byte
is a signed 8-bit integer equivalent in a Node.js buffer buf.readInt8()
.
So, you can read the required amount byte
from Buffer
in your array usingbuf.readInt8()
Or just convert it to Int8Array
:
new Int8Array(new Buffer([100, 200, 255, 1, 32]));
source to share
I would recommend that you change your JPEG file identification logic using magic numbers from the first 4 bytes, your -40 logic may not be sufficient.
FFD8FFE0 should be the first 4 bytes of a jpeg file
Hence the following Node.js program might 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 errors err and doc null are not included in this program
source to share