简体   繁体   中英

Why do byte arrays update when switching from java to javascript

I am using a tool that is sending binary data to a Ponte (Node.js) application that forwards this message (without changes) to an AMQP broker.

Overall it is: Java -> JavaScript -> Java And I do have a strange conversion of the binary data. Here are the HEX values in the order they appear:

When I prepare a binary data set it looks like this:

[4, -30, -30, -9, -115, 0, 1, 0, 1, 0, 96, -32, 46, 0, 0, 0]

When it arrives in JavaScript (Ponte) it looks like this:

[4, 226, 226, 247, 141, 0, 1, 0, 1, 0, 96, 224, 46, 0, 0, 0]

Here the negative decimals turned into positive decimals. If you "substract" those values, then you can see that they do have a value of 256

Now I am sending this data back from JavaScript to Java via an AMQP broker.

In Java my binary data now looks like this:

[4, -17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67, 0, 1, 0, 1, 0, 96, -17, -65, -67, 46, 0, 0, 0]

It is still similar like before, but all the decimals that turned from negative to positive now turned to

-17, -65, -67,

In Java I am working with byte arrays and in JavaScript I am working with a Buffer. Can anyone explain where this strange behaviour does come from?

Let me know if you need more info about my problem.

Thank you a lot!

This is clearly a signed/unsigned issue between Ponte and java

[4, -30, -30, -9, -115, 0, 1, 0, 1, 0, 96, -32, 46, 0, 0, 0]

[4, 226, 226, 247, 141, 0, 1, 0, 1, 0, 96, 224, 46, 0, 0, 0]

if yoou look carefully, negative values are turning in its complement equivlaent by adding 256 to its value...

on the Ponte side you can do the math to transform back this array into a signed 8 bits number

[4, 226, 226, 247, 141, 0, 1, 0, 1, 0, 96, 224, 46, 0, 0, 0]

just check that all numbers biggges than 127 were negative in the java side, so you need to do :

if number > 127 then number -=256

It all has to do with you (I mean the programming language) interpret 8 bits. In Java, the first bit is a sign bit, whereas in JavaScript the first bit is treated like the largest bit of the number. Data-wise, the two values are equivalent. If you want to prevent this switching, you should use a larger primitive value like a char or an int

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM