1

I am re-writing a Java Code to Java Script and i got into this Bit operation that doesn't work the same, here is the original Java Code:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.reset();
short x = 451;
bos.write(x & 0xFF);
byte[] bytesArr = bos.toByteArray();

which gives me the one cell sized array: [-61]

this is the JavaScript Code:

var bos = [];
var x = 451;
bos.push(x & 0xFF);

this gives me the one cell sized array: [195]

I have a few more numbers besides the 451 and the transformation works fine for them, what am I missing?

1
  • Have you tried to make a GWT compile? It could help you, if there is a larger codebase. Commented Dec 21, 2016 at 18:08

1 Answer 1

3

JavaScript doesn't have fixed size integers, just a single number type, so you would have to use bitwise operators (which automatically treat it as a 32-bit integer) and sign-extend the 8-bits.

var bos = [];
var x = 451;
bos.push(((451 & 0xFF) << 24) >> 24);

console.log(bos);

Or better-yet, use a typed array (you will need to know the size of your array first though).

var bos = new Int8Array(1);
bos[0] = 451;

console.log(bos);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.