0

我有一个发送一堆无符号变量的 TCP 数据包(它们是无符号的,因为它们节省空间并使用唯一 ID 的限制),我需要将此无符号短位数据转换为 java 中的整数。

所以我的问题是如何将 byteArray[0 - 15] 转换为 int?

编辑:

这是我更改为的代码:

ByteOrder order = ByteOrder.BIG_ENDIAN;
requestedDateType = new BigInteger(ByteBuffer.allocate(2).put(data, 8, 2).order(order).array()).intValue();

进来的数据缓冲区是:

bit   0    1   2   3   4   5   6   7   8   9

value 40   0   0   0   8   0   0   0   1   0

数据以 Little Endian 形式发送。我假设因为 BigInteger 假设很大,所以我需要转换为那个。然而,无论是大订单还是小订单,都给了我相同的回报。

我希望得到 1 的值,requestedDateType但是我得到 256。如何填充两个缺失的字节以确保它给我 0000 0000 0000 0001 而不是 0000 0001 0000 0000

编辑2:

没关系。将代码更改为:

ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(data, 8, 2);
int value = ((int)bb.getShort(0)) & 0xff;
4

2 回答 2

4

Use ByteBuffer in the java.nio package.

//Convert unsigned short to bytes:
//java has no unsigned short. Char is the equivalent.
char unsignedShort = 100;
//Endianess of bytes. I recommend setting explicitly for clarity
ByteOrder order = ByteOrder.BIG_ENDIAN;
byte[] ary = ByteBuffer.allocate(2).putChar(value).order(order).array();

//get integers from 16 bytes
byte[] bytes = new byte[16];
ByteBuffer buffer= ByteBuffer.wrap(bytes);
for(int i=0;i<4;i++){
    int intValue = (int)buffer.getInt();
}

Guava also has routines for primitive to byte conversion if you're interested in an external library: http://code.google.com/p/guava-libraries/

Also, I don't know your use-case, but if you're in the beginning stages of your project, I'd use Google's ProtoBufs for exchanging protocol information. It eases headaches when transitioning between protocol versions, produces highly compact binary output, and is fast.

Also if you ever change languages, you can find a protobufs library for that language and not rewrite all your protocol code.

http://code.google.com/p/protobuf/

于 2013-06-24T20:22:40.993 回答
0

我最终利用了这个资源:http ://www.javamex.com/java_equivalents/unsigned.shtml

ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(data, 8, 2);
requestedDateType = ((int)bb.getShort(0)) & 0xff;

我将这两个字节复制为一个短字节,然后将其转换为一个 int 并删除该符号。

于 2013-06-25T14:47:44.453 回答