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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.