我正在使用的协议要求将文件中的当前位置作为“无符号,网络字节顺序的4字节整数”发回。关于这个问题有几个问题,但他们假设我使用的是Integers,而不是Longs
我正在尝试将其移植到NIO的ByteBuffer,以便它可以在套接字通道中发送:
long bytesTransfered = ... some number of bytes transfered...
//TODO: What does this actually do?
outBuffer[0] = (byte) ((bytesTransfered >> 24) & 0xff);
outBuffer[1] = (byte) ((bytesTransfered >> 16) & 0xff);
outBuffer[2] = (byte) ((bytesTransfered >> 8) & 0xff);
//TODO: Why does netbeans say this does nothing?
outBuffer[3] = (byte) ((bytesTransfered >> 0) & 0xff);
他们在ByteBuffer中的任何方法都能实现这一目标吗?希望以一种更加明显的,自我描述的方式,然后上面的位移魔法?
答案 0 :(得分:6)
无论是有符号还是无符号,这些位都是相同的。
如果将long
强制转换为int
,则JVM会丢弃高位。将int
提升为long
时会出现问题:Java会对值进行签名扩展,并使用long
的最高位填充int
的高位{1}}。
要解决此问题,只需将蒙版应用于长镜头即可。以下内容应该清楚说明:
long value = Integer.MAX_VALUE + 1234L;
System.out.println("original value = " + value);
int iValue = (int)value;
System.out.println("value as int = " + iValue);
byte[] array = new byte[4];
ByteBuffer buf = ByteBuffer.wrap(array);
buf.putInt(0, iValue);
int iRetrieved = buf.getInt(0);
System.out.println("int from buf = " + iRetrieved);
long retrieved = iRetrieved;
System.out.println("converted to long = " + retrieved);
retrieved = retrieved & 0xFFFFFFFFL;
System.out.println("high bytes masked = " + retrieved);
然而,请注意您仍然只有32位。如果文件大小超过4Gb,您将无法将其装入4个字节(如果您不得不担心文件> 2G,那么您应该担心文件> 4G)。
答案 1 :(得分:3)
这正是ByteBuffer.putInt()
的用途。您说您正在使用long
,但您也只想写四个字节,因此您必须将long
转换为int
。或者使用putLong()
并获得8个字节。