2012-03-24 81 views
8

我有一个字节[4],其中包含一个32位无符号整数(以大端顺序),我需要将其转换为长(如int可以没有签名的号码)。32位无符号整数(大端)转换为长和后

此外,我怎么做反之亦然(即从long包含一个32位无符号整数字节[4])?

+0

从哪里来的字节数组? – Raffaele 2012-03-24 20:10:09

+0

@Raffaele from一个文件 – Aviram 2012-03-24 20:11:22

回答

12

听起来像是为ByteBuffer工作。

有点像

public static void main(String[] args) { 
    byte[] payload = toArray(-1991249); 
    int number = fromArray(payload); 
    System.out.println(number); 
} 

public static int fromArray(byte[] payload){ 
    ByteBuffer buffer = ByteBuffer.wrap(payload); 
    buffer.order(ByteOrder.BIG_ENDIAN); 
    return buffer.getInt(); 
} 

public static byte[] toArray(int value){ 
    ByteBuffer buffer = ByteBuffer.allocate(4); 
    buffer.order(ByteOrder.BIG_ENDIAN); 
    buffer.putInt(value); 
    buffer.flip(); 
    return buffer.array(); 
} 
+0

如果我错了,纠正我,但如果我做'int value = buffer.getInt();'然后int可能无法包含整个数字(如果它是无符号的并且没有签名) 。 – Aviram 2012-03-24 20:10:41

+0

@Aviram Java中的整数是32位(4字节),只要你的ByteBuffer是4字节长,我不明白为什么应该有问题。我已经改进了我的答案,并用积极和消极的方式对它进行了测试,到目前为止它工作得很好。我可能会错过什么吗?如果你打算使用无符号整数,那么使用long而不是整数,因为Java中的整数是有符号的。 – 2012-03-24 20:19:23

+3

您可以使用'return buffer.getInt()&0xFFFFFFFFL;',因为您将始终获得无符号值。 ByteBuffer默认为BIG_ENDIAN。你不需要调用'flip()'来使用'array()' – 2012-03-25 08:22:08

8

您可以使用字节缓冲区,或者你可以做到这一点的老式的方法:

long result = 0x00FF & byteData[0]; 
result <<= 8; 
result += 0x00FF & byteData[1]; 
result <<= 8; 
result += 0x00FF & byteData[2]; 
result <<= 8; 
result += 0x00FF & byteData[3]; 
相关问题