【发布时间】:2014-03-07 15:55:41
【问题描述】:
根据文章here,ByteBuffers 上的 compareTo 方法在处理负数时可能无法正常工作
bytes in Java are signed, contrary to what one typically expects. What is easy to miss
though, is the fact that this affects ByteBuffer.compareTo() as well. The Java API
documentation for that method reads:
"Two byte buffers are compared by comparing their sequences of remaining elements
lexicographically, without regard to the starting position of each sequence within its
corresponding buffer."
A quick reading might lead one to believe the result is what you would typically expect,
but of course given the definition of a byte in Java, this is not the case. The result
is that the order of byte buffers that contains values with the highest order bit set,
will diverge from what you may be expecting.
我尝试了几个将负值放入缓冲区的示例,并与正值进行比较,结果总是可以的。文章是在谈论我们例如的情况吗?读取二进制数据,当整数-1 存储为100000...001 时会导致问题吗?
【问题讨论】:
-
我想说的是,您可能期望的是,包含负字节的字节缓冲区会比包含正字节的字节缓冲区“更小”(在 compareTo 的上下文中),但由于签名则相反,即 -1 > 1 因为
11111111111111111111111111111111>00000000000000000000000000000001。 -
这并不神秘。 ByteBuffer.compareTo() 的 Javadoc 指出,字节的比较就像通过 Byte.compareTo() 一样,而后者又指定了有符号的比较。
标签: java nio bytebuffer compareto