Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java byteArray equivalent in JavaScript

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?

like image 700
Raj Avatar asked Jun 12 '15 07:06

Raj


People also ask

What is byte array in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

Can we convert string to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

What is a buffer array?

An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. The contents of an ArrayBuffer cannot be directly manipulated and can only be accessed through a DataView Object or one of the typed array objects. These Objects are used to read and write the contents of the buffer.


1 Answers

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]));
like image 143
zlumer Avatar answered Oct 13 '22 00:10

zlumer