Reputation: 337
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?
Upvotes: 7
Views: 14538
Reputation: 29957
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
Upvotes: 1
Reputation: 4054
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?
Upvotes: 0
Reputation: 7004
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 byte
s from Buffer
into your array using buf.readInt8()
Or just convert it into Int8Array
:
new Int8Array(new Buffer([100, 200, 255, 1, 32]));
Upvotes: 3
Reputation: 8823
You're looking for Buffer
. It allows reading/writing of variously sized binary values and random access.
Upvotes: 0