java将int转换为short [英] java converting int to short
问题描述
我正在计算我的数据的 16 位校验和,我需要将其发送到服务器,在那里它必须重新计算并与提供的校验和匹配.我得到的校验和值在 int 中,但我只有 2 个字节用于发送值.所以我在调用 shortToBytes
时将 int
转换为 short
> 方法.这工作正常,直到校验和值小于 32767,此后我得到负值.
I am calculating 16 bit checksum on my data which i need to send to server where it has to recalculate and match with the provided checksum. Checksum value that i am getting is in int but i have only 2 bytes for sending the value.So i am casting int
to short
while calling shortToBytes
method. This works fine till checksum value is less than 32767 thereafter i am getting negative values.
事实是java没有无符号原语,所以我不能发送大于允许的有符号short
最大值的值.
Thing is java does not have unsigned primitives, so i am not able to send values greater than max value of signed short
allowed.
我该如何做到这一点,将 int 转换为 short 并通过网络发送,而无需担心截断和签名 &无符号整数.
How can i do this, converting int to short and send over the network without worrying about truncation and signed & unsigned int.
在两边我都有java程序运行.
Also on both the side i have java program running.
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();
}
推荐答案
您仍然获得与服务器相同的位值.因此,要查看正确的数值,请将 ByteBuffer.wrap(baValue).getShort()
替换为 ByteBuffer.wrap(baValue).getInt()
.这应该为您提供与服务器相同的数值.
You are still getting the same bit value as the server. So, to see the right numerical value replace the ByteBuffer.wrap(baValue).getShort()
to a ByteBuffer.wrap(baValue).getInt()
. This should give you the same numerical value as the server.
这篇关于java将int转换为short的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!