简体   繁体   English

在java中将两个字节(一个正面和另一个负面)组合成短

[英]Combine two bytes (one positive and another negative ) into short in java

I am trying to port my C++ project in java. 我试图在java中移植我的C ++项目。 Down the line I have to read some bytes from serial port and combine two bytes into short. 在线下我必须从串口读取一些字节并将两个字节合并为短。 Things are working elegantly with below code. 使用下面的代码可以很好地工作。

               ByteBuffer bb = ByteBuffer.allocate(2);
                bb.order(ByteOrder.LITTLE_ENDIAN);

                bb.put(b1);
                bb.put(b2);
                  result = bb.getShort(0);

In c++ project instead of short they have unsigned short (in java we don't have unsigned). 在c ++项目而不是short中,他们有unsigned short(在java中我们没有unsigned)。

So my above logic result does not align with C++ result for below case:-
 b1 = 106 ,  b2 = -1     c++ result = 150   and java = -150


 b1 =-6, b2 =   -1     506 in VC++ but -6 in java

However, if only first byte is negative then my result are similar :
b1 = -12 ,  b2 = 1     c++ result = 500   and java = 500

I want to align my result with c++. 我想将结果与c ++对齐。 any suggestions and help would be highly appreciable . 任何建议和帮助都会非常值得注意。

Don't use getShort() , use getInt() instead. 不要使用getShort() ,而是使用getInt()

Your problem is that the most significant bit is being interpreted as the sign bit due to the fact that this is the case for a signed short. 您的问题是最重要的位被解释为符号位,因为这是签名短路的情况。 If you extend the data type so that bit is no longer considered the sign bit, you should get the behaviour you want. 如果扩展数据类型以使该位不再被视为符号位,则应该获得所需的行为。

You may need to pad out your buffer to do this: 您可能需要填充缓冲区来执行此操作:

ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.LITTLE_ENDIAN);

bb.put(b1);
bb.put(b2);
bb.put(0);
bb.put(0);

result = bb.getInt(0);

EDIT: This would work if only the C++ code was doing the right thing, but as pointed out in the comments above, it isn't (ie it is NOT simply taking the two bytes and combining them into a short. It performs some other transform on them as well). 编辑:如果只有C ++代码正在做正确的事情,这有效,但正如上面的评论所指出的那样,它不是(即它不是简单地取两个字节并将它们组合成一个短的。它执行其他一些转换它们)。

java -6 (0xFFFA) is correct, C++ 506 (0x01FA) is not. java -6(0xFFFA)是正确的,C ++ 506(0x01FA)不是。 0xFA. 0xFA回应。 Seems you mistyped -1: 1 or - -1. 似乎你错误输入-1:1或 - -1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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