将短位转换为int

时间:2013-06-24 20:21:13

标签: java

我有一个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假设很大,我需要转换为那个。但无论是大订单还是小订单都给我相同的价值。

我期望得到requestedDateType的值为1但是我得到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;

2 个答案:

答案 0 :(得分:4)

在java.nio包中使用ByteBuffer。

//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还具有原始到字节转换的例程: http://code.google.com/p/guava-libraries/

此外,我不知道您的用例,但如果您处于项目的开始阶段,我会使用Google的ProtoBufs来交换协议信息。当在协议版本之间转换时,它会减轻头痛,产生高度紧凑的二进制输出,并且速度很快。

此外,如果您更改语言,您可以找到该语言的protobufs库,而不是重写所有协议代码。

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

答案 1 :(得分: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;

我将两个字节复制成一个short,然后将其转换为int并删除了符号。

相关问题