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?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
user1322801
  • 839
  • 1
  • 12
  • 27

1 Answers1

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);
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171