我正在计算我的数据的 16 位校验和,我需要将其发送到必须重新计算并与提供的校验和匹配的服务器。我得到的校验和值在 int 中,但我只有 2 个字节用于发送值。所以我在调用方法时正在int
转换。这工作正常,直到校验和值小于 32767 之后我得到负值。short
shortToBytes
事情是java没有无符号原语,所以我无法发送大于short
允许的最大值的值。
我该如何做到这一点,将 int 转换为 short 并通过网络发送,而不用担心截断和有符号和无符号 int。
同样在双方我都有java程序运行。
private byte[] shortToBytes(short sh) {
byte[] baValue = new byte[2];
ByteBuffer buf = ByteBuffer.wrap(baValue);
return buf.putShort(sh).array();
}
private short bytesToShort(byte[] buf, int offset) {
byte[] baValue = new byte[2];
System.arraycopy(buf, offset, baValue, 0, 2);
return ByteBuffer.wrap(baValue).getShort();
}